string – TecAdmin https://tecadmin.net How to guide for System Administrator's and Developers Sat, 31 Dec 2022 18:06:24 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.1 How to Generate Random String in Python https://tecadmin.net/how-to-generate-random-string-in-python/ https://tecadmin.net/how-to-generate-random-string-in-python/#respond Tue, 27 Dec 2022 09:15:15 +0000 https://tecadmin.net/?p=33013 Generating random strings in Python is a common task that can be useful in various scenarios, such as when you need to create unique identifiers, when you want to generate random passwords, or when you want to create random data for testing purposes. In Python, you can use the random module and the string module [...]

The post How to Generate Random String in Python appeared first on TecAdmin.

]]>
Generating random strings in Python is a common task that can be useful in various scenarios, such as when you need to create unique identifiers, when you want to generate random passwords, or when you want to create random data for testing purposes. In Python, you can use the random module and the string module to generate random strings. The random module provides functions for generating random numbers, and the string module provides functions for generating random strings.

In this article, we will explore how to generate random strings in Python using these two modules.

Method 1: Using Python `secrets` Module

Here’s an example of how to use the `secrets` module to generate a random string in Python:

import secrets

random_string = secrets.token_hex(16)
print(random_string)

This code will generate a random string of 32 characters, consisting of hexadecimal digits (0-9 and a-f). The `token_hex()` function generates a secure, random string of the specified length using the `urandom()` function from the os module.

Method 1: Using Python `random` Module

You can also use the `random` module from the Python standard library to generate a random string. Here’s an example of how to do that:

import random
import string

def generate_random_string(length):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

random_string = generate_random_string(16)
print(random_string)

This code will generate a random string of 16 characters, consisting of uppercase and lowercase ASCII letters and digits. The `generate_random_string()` function uses the `random.choice()` function to randomly select characters from the string.ascii_letters and string.digits strings, and then it uses the `join()` function to combine them into a single string.

Conclusion

In conclusion, generating random strings in Python is a useful task that can be easily accomplished using the random module and the string module. The `random` module provides functions for generating random numbers, and the string module provides functions for generating random strings. By combining these two modules, you can generate random strings of any length and complexity. Understanding how to generate random strings in Python can be helpful in various scenarios, such as when you need to create unique identifiers, when you want to generate random passwords, or when you want to create random data for testing purposes.

I hope this helps! Let me know if you have any questions.

The post How to Generate Random String in Python appeared first on TecAdmin.

]]>
https://tecadmin.net/how-to-generate-random-string-in-python/feed/ 0
Comparing Strings in Bash: Techniques and Best Practices https://tecadmin.net/compare-strings-in-bash/ https://tecadmin.net/compare-strings-in-bash/#respond Sun, 09 Oct 2022 16:29:36 +0000 https://tecadmin.net/?p=6644 Comparing strings is a common task when working with shell scripts, user input, or string data. In the shell, you may need to check if a value exists in another string, find if two strings have the same length, test for the beginning or end of a word, or any other type of comparison. The [...]

The post Comparing Strings in Bash: Techniques and Best Practices appeared first on TecAdmin.

]]>
Comparing strings is a common task when working with shell scripts, user input, or string data. In the shell, you may need to check if a value exists in another string, find if two strings have the same length, test for the beginning or end of a word, or any other type of comparison. The standard Unix tools don’t provide many options for comparing strings; the traditional lexical comparison (like checking if two words are the same length and comparing each character individually) is hard to implement efficiently in code and isn’t as valuable for a dynamic language like Bash.

This article explains different ways to compare strings in Bash and several related commands.

String Comparison Operators

We can use comparison operators with bash if statements to compare two strings. Here is the list of comparison operators to work with strings in the bash shell.

Operator Details
string1 == string2 Returns true if both strings are equal.
string1 != string Returns true if both strings are not equal.
string =~ regex Compare string1 with regular expression and return true matches
-z string Return true if the given string length is zero (0)
-n string Return true if the given string length is not zero

Now, we will discuss the above comparison operator one by one with examples.

Compare Two Strings in Bash (==)

If you need to check if two strings are equal, use the == operator. These operators compare the left operand with the right operand and return true if both match.

Let’s understand with an example. In a shell script initialize two variables with a string. Then use the if statement to compare whether both strings are equal or not using the == operator.

#!/usr/bin/env bash

STR1="TecAdmin"
STR2="TecAdmin"

if [ "$STR1" == "$STR2" ]
then
    echo "Both strings are equal"
else
    echo "Both strings are not equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
Both strings are equal

Now, change both variables’ values with different strings. Then again the script and see the results.

Check Two Strings are Not Equal (!=)

Sometimes we are required to check if both strings are not equal. You can use != operator to test if two strings are not equal. Let’s check with an example:

#!/usr/bin/env bash

STR1="TecAdmin"
STR2="HelloWorld"

##Check if both strings are not equal
if [ "$STR1" != "$STR2" ]
then
    echo "True, both strings are not equal"
else
    echo "False, both strings are equal"
fi

Run the above shell script in a bash shell and check for the results.

Output:
True, both strings are not equal

Compare Strings with Regular Expression

We can also compare string with a regular expression in bash scripts. While using the string comparison with regular expression with an if statement, you should always enclose with [[ ]] quotes. The below example will show help you to check if the variable contains the string that begins with a specific string.

#!/usr/bin/env bash

STR="TecAdmin"

if [[ "$STR" =~ ^Tec ]]
then
    echo "Yes, the regular expression matches "
else
    echo "Regular expression not matches "
fi

Output:
Yes, the regular expression matches

Let’s check with another example. In this script, we will prompt the user to input a number. Then verify whether the input value is a number or not. A number container the digits between 0 to 9.

#!/usr/bin/env bash

read -p "Input a number: " VAR

## Check if the input value is a number
if [[ "$VAR" =~ ^[0-9]+$ ]]
then
    echo "Given input is a number"
else
    echo "Sorry, input is not a number"
fi

Run the above bash script and provide the input when prompted.

First run:
Input a number: 12
Given input is a number

Again run this script but this time input a non-numeric value and see the results.

Second run:
Input a number: 1234a
Sorry, input is not a number

Check if a String is Empty

While taking user input in a shell script, it’s important to check that the input string is not empty. You can use -z returns true if the string is empty.

#!/usr/bin/env bash

read -p "Type anything: " VAR

if [[ -z $VAR ]]; then
  echo "Empty string"
else
  echo "You type: ${VAR}"
fi

Execute the above shell script in a bash shell and just hit enter when prompted for user input.

First run:
Type anything:
Empty string

Again run the above script and type something when prompted.

Second run:
Type anything: TecAdmin
You type: TecAdmin

Conclusion

In this tutorial, we have discussed string comparisons in the bash script. You can also check if a string is empty or not. Also provides an example to check if the input value is a number or not.

The post Comparing Strings in Bash: Techniques and Best Practices appeared first on TecAdmin.

]]>
https://tecadmin.net/compare-strings-in-bash/feed/ 0
Convert String to Lowercase in Bash – Easier Than You Think https://tecadmin.net/convert-string-to-lowercase-in-bash/ https://tecadmin.net/convert-string-to-lowercase-in-bash/#respond Mon, 01 Aug 2022 10:03:47 +0000 https://tecadmin.net/?p=30813 Question: How do I convert all the characters to the lowercase of a string in the bash shell script? In Linux, the tr command is used to translate, squeeze, and/or delete characters. So with the help of the tr command, you can convert the case of any character. You can do this quickly with a [...]

The post Convert String to Lowercase in Bash – Easier Than You Think appeared first on TecAdmin.

]]>
Question: How do I convert all the characters to the lowercase of a string in the bash shell script?

In Linux, the tr command is used to translate, squeeze, and/or delete characters. So with the help of the tr command, you can convert the case of any character. You can do this quickly with a single-line command.

You can use the following command to convert a string to lowercase. Here the command takes the standard input of a string and processes it.

echo "Input string here" | tr '[:upper:]' '[:lower:]' 

Let’s discuss with an example.

Example

Let’s create a sample shell script. Initialize a variable with a string having a few uppercase letters. Then convert all the letters to lowercase and store them in another variable.

#!/usr/bin/env bash

str="Hello World"
lowerStr=$(echo "$str" | tr '[:upper:]' '[:lower:]')

echo "Input String: $str"
echo "Result String:  $lowerStr"

Run the above script and see the results:

Output:
Input String: Hello World Result String: hello world

You can see the result string has all the characters in lowercase.

The post Convert String to Lowercase in Bash – Easier Than You Think appeared first on TecAdmin.

]]>
https://tecadmin.net/convert-string-to-lowercase-in-bash/feed/ 0
How to Replace String in JavaScript https://tecadmin.net/replace-string-in-javascript/ https://tecadmin.net/replace-string-in-javascript/#respond Mon, 13 Jun 2022 10:01:33 +0000 https://tecadmin.net/?p=23713 We can use replace() method to replace any string or character with another in javascript. It searches for a defined string, character, or regular expression and replaces it. This method doesn’t change the original string but it returns the updated string as result. Syntax: string.replace(old_string, new_string) Replace String in JavaScript with Examples In this tutorial, [...]

The post How to Replace String in JavaScript appeared first on TecAdmin.

]]>
We can use replace() method to replace any string or character with another in javascript. It searches for a defined string, character, or regular expression and replaces it. This method doesn’t change the original string but it returns the updated string as result.

Syntax:

string.replace(old_string, new_string)

Replace String in JavaScript with Examples

In this tutorial, we will discuss a few examples of replacing strings in Javascript.

Let’s try some examples:

  • Here is the first example to initialize a text in a variable, then replace it with another text.

    let str = "Hello World!"
    let result = str.replace("World", "TecAdmin")
    
    console.log(result)

    Run the above example and see the results. Thanks to playcode.io that help me to run javascript online.

    How to Replace String in JavaScript
    Replace string in javascript
  • What happens if a given string is found multiple times. In that case, the replace() function will replace the first occurrence of the given string.

    let str = "Mr Bean has a green Apple and a Red Apple"
    
    let result = str.replace("Apple", "Strawberries")
    
    console.log(result)

    Execute the above code and see the results:

    Replace first matching string in javascript
    Replace first matching string in javascript

    The result clearly shows that the first occurrence is replaced with a new string, but the second occurrence is not replaced. So, how can I replace all the occurrences of a given string? Let’s check the next example:

  • We can also define the regular expression and the function will replace all occurrences matching that regular expression.

    See the below example, where we defined a regular expression to replace string globally.

    let str = "Mr Bean has a green Apple and a red Apple"
    
    const regex = "/Apple/ig"
    let result = str.replace("Apple", "Strawberries")
    
    console.log(result)

    Run the above example and see the results.

    Replace string with regular expression in JavaScript
    Replace string with regular expression in JavaScript
  • Basically, the regular expression is used to match patterns. To replace all occurrences of any string, we can use replaceAll() function.

    The below example uses the replaceAll() function in javascript.

    let str = "Mr Bean has a green Apple and a red Apple"
    
    let result = str.replaceAll("Apple", "Strawberries")
    
    console.log(result)

    Run the above code and see the results.

    Replace all matching string in JavaScript
    Replace all matching strings in JavaScript

Wrap Up

In this tutorial, we have discussed a few examples to replace a string in javascript.

The post How to Replace String in JavaScript appeared first on TecAdmin.

]]>
https://tecadmin.net/replace-string-in-javascript/feed/ 0
Bash – Remove Double Quote (“”) from a String https://tecadmin.net/bash-remove-double-quote-string/ https://tecadmin.net/bash-remove-double-quote-string/#comments Sun, 11 Apr 2021 09:35:06 +0000 https://tecadmin.net/?p=25180 This tutorial will help you to remove the start and ending double quotes from strings in a shell script. Where the string is stored in a variable. Remove Double Quote from a String The sed command line utility helps to easily handle this. A single-line sed command can remove quotes from the start and end [...]

The post Bash – Remove Double Quote (“”) from a String appeared first on TecAdmin.

]]>
This tutorial will help you to remove the start and ending double quotes from strings in a shell script. Where the string is stored in a variable.

Remove Double Quote from a String

The sed command line utility helps to easily handle this. A single-line sed command can remove quotes from the start and end of the string.

sed -e 's/^"//' -e 's/"$//' <<<"$var1" 

The above sed command executes two expressions against the variable value.

  • The first expression 's/^"//' will remove the starting quote from the string.
  • Second expression 's/"$//' will remove the ending quote from the string.

Shell Script Remove Double Quote from String

Remove Double Quote and Store Output

The result will be printed on the terminal. You can also save the result to a variable and or redirect output to a file.

The below commands will help you to remove double quotes and store output to the same or different variable.

var2=`sed -e 's/^"//' -e 's/"$//' <<<"$var1"`    #Save in another variable 
var1=`sed -e 's/^"//' -e 's/"$//' <<<"$var1"`    #Save in same variable 

Even you can store the result in a file. like:

sed -e 's/^"//' -e 's/"$//' <<<"$var1" > out_var.txt 

Conclusion

This tutorial helped you to remove the start and ending double quotes from a string stored in a variable using shell script.

The post Bash – Remove Double Quote (“”) from a String appeared first on TecAdmin.

]]>
https://tecadmin.net/bash-remove-double-quote-string/feed/ 3
Remove First Character from String in JavaScript https://tecadmin.net/remove-first-character-from-string-in-javascript/ https://tecadmin.net/remove-first-character-from-string-in-javascript/#respond Tue, 02 Mar 2021 07:04:52 +0000 https://tecadmin.net/?p=24856 Question – How to remove first character of a string using JavaScript ? In the previous article, you have learned to remote last character of a string in JavaScript. If you are looking for remove last character from string, visit here. This tutorial describe you to how to remove first character of a string in [...]

The post Remove First Character from String in JavaScript appeared first on TecAdmin.

]]>
Question – How to remove first character of a string using JavaScript ?

In the previous article, you have learned to remote last character of a string in JavaScript. If you are looking for remove last character from string, visit here. This tutorial describe you to how to remove first character of a string in JavaScript. You can choose any one of the following methods.

Method 1 – Using substring() function

Use the substring() function to remove the last character from a string in JavaScript. This function returns the part of the string between the start and end indexes, or to the end of the string.

Example

<script>
  var str= "Hello TecAdmin!";
  var newStr = str.substring(1, str.length);
  console.log(newStr);
</script>

Output:

ello TecAdmin!

Method 2 – Using slice() function

Use the slice function to remove the last character from any string in JavaScript. This function extracts a part of any string and return as new string. When you can store in a variable.

Example:

<script>
  var str = "Hello TecAdmin!";
  var newStr = str.slice(1);
  console.log(newStr);
</script>

Output:

ello TecAdmin!

Conclusion

In this tutorial, you have learned how to remove first character from a string using JavaScript. You can also read our next tutorial to trim white spaces from string.

The post Remove First Character from String in JavaScript appeared first on TecAdmin.

]]>
https://tecadmin.net/remove-first-character-from-string-in-javascript/feed/ 0
How To Convert String to Integer in Python https://tecadmin.net/python-convert-string-to-int/ https://tecadmin.net/python-convert-string-to-int/#respond Sun, 22 Nov 2020 17:43:34 +0000 https://tecadmin.net/?p=19503 A string is a sequence of characters, numbers, and special characters together. An integer is a set of numbers that includes zero, negative and positive numbers without any decimal or fractional parts. Datatype is a classification of data, which tells the compiler or interpreter, how the programmer intends to use the data. Similar to other [...]

The post How To Convert String to Integer in Python appeared first on TecAdmin.

]]>
A string is a sequence of characters, numbers, and special characters together. An integer is a set of numbers that includes zero, negative and positive numbers without any decimal or fractional parts. Datatype is a classification of data, which tells the compiler or interpreter, how the programmer intends to use the data. Similar to other programming languages Python also supports datatype conversions.

This tutorial describes how to convert a Python string to int and vice versa.

Python Convert String to int

Use Python int() function to convert a string value to integer in Python. This function accepts two parameters, one is the string in quotes and the second is an optional base to represent the data.

Use the following syntax to return the string value as an integer

int("number", base=base)

Open a Python shell to run tests below:

>>> print(int("100"))
100

You can also check the type of value stored in a variable. Like, store a number as a string to a variable and verify that the type is “str”. Next, convert the Python string to int and again check the type of value. You will find that the type of value is int.

# Assign a number as string to variable
>>> s = "100"

# Check the datatype
>>> type(s)
<type 'str'>


# Python Convert string to int
>>> s = int(s)

# Again check the datatype
>>> type(s)
<type 'int'>

The input must contain numerical values (0-9), nothing else.

For example, if the input value contains non-numeric values (like alphabets, symbols) will throw an error with invalid literal. See the example below:

>>> s = '10e'
>>>
>>> s = int(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10v0'

Python Convert Integer to String

You can also convert a numeric value to a string value. Use the python str() function to convert an integer value to a string.

The Python str() function syntax is:

str(number)

Run an example in the Python console.

>>> print(str(100))
100

Run a demonstration of type conversion by verifying the data type. Run the below commands in the Python shell one by one.

# Assign a number as inter to variable
>>> s = 100

# Check the datatype
>>> type(s)
<class 'int'>


# Convert integer to string 
>>> s = str(s)

# Again check the datatype
>>> type(s)
<class 'str'>

You can see that the first time the datatype is showing to “int”. After the type conversion with the Python str() function, the new datatype is showing to “str”.

Conclusion

The Python int() method is used to convert a string value to an integer value. This is useful to perform mathematical operations on a numeric value stored as a string.

Suggested reading: Here are more useful examples of string conversions in the Python programming languages.

The post How To Convert String to Integer in Python appeared first on TecAdmin.

]]>
https://tecadmin.net/python-convert-string-to-int/feed/ 0
How to check if string contains specific word in PHP https://tecadmin.net/check-if-string-contains-specific-word-in-php/ https://tecadmin.net/check-if-string-contains-specific-word-in-php/#comments Thu, 20 Jun 2019 10:28:17 +0000 https://tecadmin.net/?p=18625 This tutorial will help you to check if a string contains any substring in PHP programming language. For example, you want to run a specific line of code only if an input string contains another substring in it. Here is a sample PHP programme, which will evaluate to true because the main string $str contains [...]

The post How to check if string contains specific word in PHP appeared first on TecAdmin.

]]>
This tutorial will help you to check if a string contains any substring in PHP programming language. For example, you want to run a specific line of code only if an input string contains another substring in it.

Here is a sample PHP programme, which will evaluate to true because the main string $str contains the substring ‘TecAdmin‘ in it. This will print “true”.

<?php
$str = 'Welcome to Tecadmin';

if (strpos($str, 'Tecadmin') !== false) {
    echo 'true';
}
?>

Another PHP program will evaluate to false because the main string $str doesn’t contains the substring ‘Hello‘ in it. This will nothing print.

<?php
$str = 'Welcome to Tecadmin';
$substr = "Hello";

if (strpos($str, $substr) !== false) {
    echo 'true';
}
?>

The post How to check if string contains specific word in PHP appeared first on TecAdmin.

]]>
https://tecadmin.net/check-if-string-contains-specific-word-in-php/feed/ 1
How to Append an Item to Array in PHP https://tecadmin.net/append-item-to-array-in-php/ https://tecadmin.net/append-item-to-array-in-php/#respond Sun, 22 Jul 2018 07:20:15 +0000 https://tecadmin.net/?p=16573 Question – How to Append an Item to Array in PHP. How do I append any element to end of the existing Array in PHP? How to push element to array in PHP? This tutorial uses array_push() function to insert or append a new element to end of the Array. PHP – Append Element to [...]

The post How to Append an Item to Array in PHP appeared first on TecAdmin.

]]>
Question – How to Append an Item to Array in PHP. How do I append any element to end of the existing Array in PHP? How to push element to array in PHP?

This tutorial uses array_push() function to insert or append a new element to end of the Array.

PHP – Append Element to Array

The following example creates an initial array with two elements (as “black”,”blue”). After that add use array_push() function to append new element “white” to the array.

<?php
  $arr = array("black","blue");
  array_push($arr, "white");

  //View final array
  print_r($arr);
?>

Output:

Array
(
    [0] => black
    [1] => blue
    [2] => white
)

The post How to Append an Item to Array in PHP appeared first on TecAdmin.

]]>
https://tecadmin.net/append-item-to-array-in-php/feed/ 0
2 Methods to Remove Last Character from String in JavaScript https://tecadmin.net/remove-last-character-from-string-in-javascript/ https://tecadmin.net/remove-last-character-from-string-in-javascript/#comments Sun, 15 Jul 2018 04:44:30 +0000 https://tecadmin.net/?p=16552 Question: How do I remove the last character from a string in JavaScript or Node.js script? This tutorial describes 2 methods to remove the last character from a string in JavaScript programming language. You can use any one of the following methods as per the requirements. Method 1 – Using substring() function Use the substring() [...]

The post 2 Methods to Remove Last Character from String in JavaScript appeared first on TecAdmin.

]]>
Question: How do I remove the last character from a string in JavaScript or Node.js script?

This tutorial describes 2 methods to remove the last character from a string in JavaScript programming language. You can use any one of the following methods as per the requirements.

Method 1 – Using substring() function

Use the substring() function to remove the last character from a string in JavaScript. This function returns the part of the string between the start and end indexes, or to the end of the string.

Syntax:

str.substring(0, str.length - 1);

Example:

// Initialize variable with string
var str = "Hello TecAdmin!";

// Remove last character of string
str = str.substring(0, str.length - 1);

// Print result string
console.log(str)

Remove last character of string with substring function
Remove last character of string with substring function

Method 2 – Using slice() function

Use the slice() function to remove the last character from any string in JavaScript. This function extracts a part of any string and return as new string. When you can store in a variable.

Syntax:

str.slice(0, -1);

Example:

// Initialize variable with string
var str = "Hello TecAdmin!";

// Remove last character of string
str = str.slice(0, -1);

// Print result string
console.log(str)

Remove last character of string with javascript slice function
Remove last character of string with javascript slice function

Wrap Up

In this tutorial, you have learned about removing the last character of a sting in JavaScript. We used substring() and slice() functions to alter a string.

The post 2 Methods to Remove Last Character from String in JavaScript appeared first on TecAdmin.

]]>
https://tecadmin.net/remove-last-character-from-string-in-javascript/feed/ 3