Python

Python hashlib.sha3_256() Function

Python hashlib Module:

To generate a message digest or secure hash from the source message, we can utilize the Python hashlib library.

The hashlib module is required to generate a secure hash message in Python.

The hashlib hashing function in Python takes a variable length of bytes and converts it to a fixed-length sequence. This function only works in one direction. This means that when you hash a message, you obtain a fixed-length sequence. However, those fixed-length sequences do not allow you to obtain the original message.

A hash algorithm is considered better in cryptography if the original message cannot be decoded from the hash message. Changing one byte in the original message also has a big impact(change) on the message digest value.

Python secure hash values are used to store encrypted passwords. So that even the application’s owner does not have access to the user’s password, passwords are matched when the user enters the password again, and the hash value is calculated and compared to the stored value.

Hashing Algorithms That Are Available:

  • The algorithms_available function returns a list of all the algorithms available in the system, including those accessible via OpenSSl. Duplicate algorithm names can also be found.
  • The algorithms in the module can be viewed by using the algorithms_guaranteed function.
import hashlib
# Printing list of all the algorithms
print(hashlib.algorithms_available)
# Viewing algorithms
print(hashlib.algorithms_guaranteed)

Output:

{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}
{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}

Functions:

You only need to know a few functions to use the Python hashlib module.

  • You can hash the entire message at once by using the hashlib.encryption_algorithm_name(b”message”) function.
  • Additionally, the update() function can be used to append a byte message to the secure hash value. The output will be the same in both cases. Finally, the secure hash can be obtained by using the digest() function.
  • It’s worth noting that b is written to the left of the message to be hashed. This b indicates that the string is a byte string.

hashlib.sha3_256() Function:

We can convert a normal string in byte format to an encrypted form using the hashlib.sha3_256() function. Passwords and important files can be hashed to secure them using the hashlib.sha3_256() method.

Syntax:

hashlib.sha3_256()

Return Value:

The hash code for the string given is returned by the sha3_256() function.

Differences

Shortly after the discovery of cost-effective brute force operations against SHA-1, SHA-2 was created. It is a family of two similar hash algorithms, SHA-256 and SHA-512, with varying block sizes.

  • The fundamental distinction between SHA-256 and SHA-512 is word size.
  • SHA-256 uses 32-byte words, whereas SHA-512 employs 64-byte words.
  • Each standard also has modified versions called SHA-224, SHA-384, SHA-512/224, and SHA-512/256. Today, the most often used SHA function is SHA-256, which provides adequate safety at current computer processing capabilities.
  • SHA-384 is a cryptographic hash that belongs to the SHA-2 family. It generates a 384-bit digest of a message.
  • On 64-bit processors, SHA-384 is around 50% faster than SHA-224 and SHA-256, despite having a longer digest. The increased speed is due to the internal computation using 64-bit words, whereas the other two hash algorithms use 32-bit words.
  • For the same reason, SHA-512, SHA-512/224, and SHA-512/256 are faster on 64-bit processors.

Algorithm – digest size (the larger the better):

MD5 –> 128 bits
SHA-1 –> 160 bits
SHA-256 –> 256 bits
SHA-512 –> 512 bits

hashlib.sha3_256() Function in Python

Method #1: Using sha3_256() Function (Static Input)

Here, we encrypt the byte string or passwords to secure them using the hashlib.sha3_256() function.

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_256() function and store it in a variable
  • Give the string as static input(here b represents byte string) and store it in another variable.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_256() function and store it in a variable
obj = hashlib.sha3_256()

# Give the string as static input(here b represents byte string) and store it in another variable.
gvn_str = b'Python-programs'

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

b'\xf7\x97[\xc6b{ua\x90bn\xbb\xf54\xc4$\xab\x08\xde\xe6\x11\xb3\xd3\xca\x99_\x89\x0b\xa99>\x9c'

Method #2: Using sha3_256() Function (User Input)

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_256() function and store it in a variable
  • Give the string as user input using the input() function and store it in another variable.
  • Convert the given string into a byte string using the bytes() function by passing the given string, ‘utf-8’ as arguments to it.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_256() function and store it in a variable
obj = hashlib.sha3_256()

# Give the string as user input using the input() function and store it in another variable.
gvn_str = input("Enter some random string = ")
# Convert the given string into byte string using the bytes() function by passing given string, 
# 'utf-8' as arguments to it 
gvn_str=bytes(gvn_str, 'utf-8')

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

Enter some random string = welcome to Python-programs
b'\xd2\xd5!\xb3\xe4\xfaM\x93</8#\xf7\xa1\xdb\xces\nE^\xc1\xb2ukW\x8eF\x8e\xa0y\x8c\x05'

Python hashlib.sha3_384() Function

Python hashlib Module:

To generate a message digest or secure hash from the source message, we can utilize the Python hashlib library.

The hashlib module is required to generate a secure hash message in Python.

The hashlib hashing function in Python takes a variable length of bytes and converts it to a fixed-length sequence. This function only works in one direction. This means that when you hash a message, you obtain a fixed-length sequence. However, those fixed-length sequences do not allow you to obtain the original message.

A hash algorithm is considered better in cryptography if the original message cannot be decoded from the hash message. Changing one byte in the original message also has a big impact(change) on the message digest value.

Python secure hash values are used to store encrypted passwords. So that even the application’s owner does not have access to the user’s password, passwords are matched when the user enters the password again, and the hash value is calculated and compared to the stored value.

Hashing Algorithms That Are Available:

  • The algorithms_available function returns a list of all the algorithms available in the system, including those accessible via OpenSSl. Duplicate algorithm names can also be found.
  • The algorithms in the module can be viewed by using the algorithms_guaranteed function.
import hashlib
# Printing list of all the algorithms
print(hashlib.algorithms_available)
# Viewing algorithms
print(hashlib.algorithms_guaranteed)

Output:

{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}
{'sha384', 'blake2s', 'sha3_384', 'sha224', 'md5', 'shake_256', 'blake2b', 'sha3_512', 'sha1', 'shake_128', 'sha512', 'sha3_256', 'sha256', 'sha3_224'}

Functions:

You only need to know a few functions to use the Python hashlib module.

  • You can hash the entire message at once by using the hashlib.encryption_algorithm_name(b”message”) function.
  • Additionally, the update() function can be used to append a byte message to the secure hash value. The output will be the same in both cases. Finally, the secure hash can be obtained by using the digest() function.
  • It’s worth noting that b is written to the left of the message to be hashed. This b indicates that the string is a byte string.

hashlib.sha3_384() Function:

We can convert a normal string in byte format to an encrypted form using the hashlib.sha3_384() function. Passwords and important files can be hashed to secure them using the hashlib.sha3_384() method.

Syntax:

hashlib.sha3_384()

Return Value:

The hash code for the string given is returned by the sha3_384() function.

Differences

Shortly after the discovery of cost-effective brute force operations against SHA-1, SHA-2 was created. It is a family of two similar hash algorithms, SHA-256 and SHA-512, with varying block sizes.

  • The fundamental distinction between SHA-256 and SHA-512 is word size.
  • SHA-256 uses 32-byte words, whereas SHA-512 employs 64-byte words.
  • Each standard also has modified versions called SHA-224, SHA-384, SHA-512/224, and SHA-512/256. Today, the most often used SHA function is SHA-256, which provides adequate safety at current computer processing capabilities.
  • SHA-384 is a cryptographic hash that belongs to the SHA-2 family. It generates a 384-bit digest of a message.
  • On 64-bit processors, SHA-384 is around 50% faster than SHA-224 and SHA-256, despite having a longer digest. The increased speed is due to the internal computation using 64-bit words, whereas the other two hash algorithms use 32-bit words.
  • For the same reason, SHA-512, SHA-512/224, and SHA-512/256 are faster on 64-bit processors.

Algorithm – digest size (the larger the better):

MD5 –> 128 bits
SHA-1 –> 160 bits
SHA-256 –> 256 bits
SHA-512 –> 512 bits

hashlib.sha3_384() Function in Python

Method #1: Using sha3_384() Function (Static Input)

Here, we encrypt the byte string or passwords to secure them using the hashlib.sha3_384() function.

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_384() function and store it in a variable
  • Give the string as static input(here b represents byte string) and store it in another variable.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_384() function and store it in a variable
obj = hashlib.sha3_384()

# Give the string as static input(here b represents byte string) and store it in another variable.
gvn_str = b'Python-programs'

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

b'\xf5;.\x1f\xb3$\xfd\xc2s7\xa5\x13\xa9\xc9\xceB\xd1A,u\x7fy\xeaw\xab\x07\x0b,lN\xefg\x86\x04t\xb0~\xd9\xe4_\xed\xc2\x07\xdb\xad$\xf4\xea'

Method #2: Using sha3_384() Function (User Input)

Approach:

  • Import hashlib module using the import keyword
  • Create a reference/Instance variable(Object) for the hashlib module and call sha3_384() function and store it in a variable
  • Give the string as user input using the input() function and store it in another variable.
  • Convert the given string into a byte string using the bytes() function by passing the given string, ‘utf-8’ as arguments to it.
  • Call the update() function using the above-created object by passing the above-given string as an argument to it
  • Here it converts the given string in byte format to an encrypted form.
  • Get the secure hash using the digest() function.
  • The Exit of the Program.

Below is the implementation:

# Import hashlib module using the import keyword
import hashlib

# Creating a reference/Instance variable(Object) for the hashlib module and 
# call sha3_384() function and store it in a variable
obj = hashlib.sha3_384()

# Give the string as user input using the input() function and store it in another variable.
gvn_str = input("Enter some random string = ")
# Convert the given string into byte string using the bytes() function by passing given string, 
# 'utf-8' as arguments to it 
gvn_str=bytes(gvn_str, 'utf-8')

# Call the update() function using the above created object by passing the above given string as 
# an argument to it
# Here it converts the given string in byte format to an encrypted form.
obj.update(gvn_str)
# Get the secure hash using the digest() function.
print(obj.digest())

Output:

Enter some random string = welcome to Python-programs
b'\xe4\xf2\xe03\xcbG\xe5YH.\xe2\x13W\xbc\xd0pQ\xd4dYshc=\xdc\xeeY\xf9\xa5dX\xda\x8c\x08\x18\xa1\xe4,\xe6z\x99x\xf2\xa4l\xe4\xc4$'

Python Numpy matrix.nonzero() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.nonzero() Function:

we can obtain the index value of a nonzero value from a specified matrix using the matrix.nonzero() function of the NumPy module. It always returns a two-dimensional array.

Syntax:

 matrix.nonzero()

Return Value:

The index value of the nonzero value from the given matrix is returned by the nonzero() function.

Numpy matrix.nonzero() Function in Python

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix.
  • Store it in another variable
  • Print the index values of nonzero elements from the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 0; 6, 3]')
            
# Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix
# Store it in another variable
rslt = gvn_matrx.nonzero()
# Print the index values of nonzero elements from the given matrix
print("The index values of nonzero elements from the given matrix:")
print(rslt)

Output:

The index values of nonzero elements from the given matrix:
(array([0, 1, 1]), array([0, 0, 1]))

For 3-Dimensional (3D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as an argument to it and store it in a variable
  • Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix.
  • Store it in another variable
  • Print the index values of nonzero elements from the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[0, 4, 1; 8, 0, 3; 0, 9, 5]')
            
# Apply nonzero() function on the given matrix to get the index values of nonzero elements from the given matrix
# Store it in another variable
rslt = gvn_matrx.nonzero()
# Print the index values of nonzero elements from the given matrix
print("The index values of nonzero elements from the given matrix:")
print(rslt)

Output:

The index values of nonzero elements from the given matrix:
(array([0, 0, 1, 1, 2, 2]), array([1, 2, 0, 2, 1, 2]))

Python Numpy matrix.partition() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.partition() Function:

Using the matrix.partition() method of the Numpy module, we can partition the matrix in such a manner that the index value that we pass sorts the matrix in such a way that all the values smaller than that value are moved to the left, and others are moved to the right.

Syntax:

 matrix.partition(index)

Return Value:

The partitioned matrix is returned by the partition() function.

Numpy matrix.partition() Function in Python

For 1-Dimensional (1D) Matrix(array)

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(1-Dimensional) using the matrix() function of numpy module by passing some random 1D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply partition() function on the given matrix by passing some random index value as an argument to it to partition the given matrix.
  • Here index value = 3, and the value at that 3rd index is 4. The values less than 4 (i.e, 1,2) are moved to the left, and others (6) are moved to the right.
  • Print the given matrix after partition.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(1-Dimensional) using the matrix() function of numpy module by passing 
# some random 1D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 1, 6, 4]')
# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply partition() function on the given matrix by passing some random index value as an argument to it
# to partition the given matrix.
# Here index value = 3, the value at the 3rd index is 4. The values less than 4 (i.e, 1,2) are 
# moved to the left and others (6) are moved to the right
gvn_matrx.partition(3)
# Print the given matrix after partition.
print("The given matrix after partition is:")
print(gvn_matrx)

Output:

The given matrix is:
[[2 1 6 4]]
The given matrix after partition is:
[[1 2 4 6]]

Explanation:

Here index value = 3, the value at the 3rd index is 4. 
The values less than 4 (i.e, 1 and 2) are moved to the left and 
other number 6 is moved to the right

For 2-Dimensional (2D) Matrix

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as an argument to it and store it in a variable
  • Print the given matrix
  • Apply partition() function on the given matrix by passing some random index value as an argument to it to partition the given matrix.
  • Print the given matrix after partition.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[10, 1; 2, 7]')
# Print the given matrix
print("The given matrix is:") 
print(gvn_matrx)   

# Apply partition() function on the given matrix by passing some random index value as an argument to it
# to partition the given matrix.
gvn_matrx.partition(1)
# Print the given matrix after partition.
print("The given matrix after partition is:")
print(gvn_matrx)

Output:

The given matrix is:
[[10 1]
 [ 2 7]]
The given matrix after partition is:
[[ 1 10]
 [ 2 7]]

Python Numpy matrix.itemset() Function

NumPy Library 

NumPy is a library in python that is created to work efficiently with arrays in python. It is fast, easy to learn, and provides efficient storage. It also provides a better way of handling data for the process. We can create an n-dimensional array in NumPy. To use NumPy simply have to import it into our program and then we can easily use the functionality of NumPy in our program.

NumPy is a Python library that is frequently used for scientific and statistical analysis. NumPy arrays are grids of the same datatype’s values.

Numpy matrix.itemset() Function:

We can set the items in a given matrix using the matrix.itemset() method of the Numpy module by passing the index number and the item as arguments.

Syntax:

 matrix.itemset(index, item)

Return Value:

A new matrix containing item is returned by the itemset() function.

Numpy matrix.itemset() Function in Python

For 2-Dimensional (2D) Matrix 

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing some random 2D matrix as arguments to it and store it in a variable
  • Pass the index(row, column) and item/value as an argument to the itemset() function and apply it to the given matrix.
  • Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
  • Store it in another variable
  • Print the given matrix after inserting an item at the specified index.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(2-Dimensional) using the matrix() function of numpy module by passing 
# some random 2D matrix as arguments to it and store it in a variable
gvn_matrx = np.matrix('[2, 1; 6, 3]')
            
# Pass the index(row, column) and item/value as an argument to the itemset() function and 
# apply it to the given matrix.
# Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
# Store it in another variable
gvn_matrx.itemset((0, 1), 50)
# Print the given matrix after inserting an item at the specified index
print("The given matrix after inserting an item {50} at the specified index(0th row, 1st col):")
print(gvn_matrx)

Output:

The given matrix after inserting an item {50} at the specified index(0th row, 1st col):
[[ 2 50]
 [ 6 3]]

For 3-Dimensional (3D) Matrix 

Approach:

  • Import numpy module using the import keyword
  • Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing some random 3D matrix as arguments to it and store it in a variable
  • Pass the index(row, column) and item/value as an argument to the itemset() function and apply it to the given matrix.
  • Here it inserts the given item at the specified index in a matrix(inserts 50 at 0th row, 1st col).
  • Store it in another variable
  • Print the given matrix after inserting an item at the specified index.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
            
# Create a matrix(3-Dimensional) using the matrix() function of numpy module by passing 
# some random 3D matrix as an argument to it and store it in a variable
gvn_matrx = np.matrix('[2, 4, 1; 8, 7, 3; 10, 9, 5]')
            
# Pass the index(row, column) and item/value as an argument to the itemset() function and 
# apply it to the given matrix.
# Here it inserts the given item at the specified index in a matrix(inserts 100 at 1st row, 2nd col).
# Store it in another variable
gvn_matrx.itemset((1, 2), 100)
# Print the given matrix after inserting an item at the specified index
print("The given matrix after inserting an item {100} at the specified index(1st row, 2nd col):")
print(gvn_matrx)

Output:

The given matrix after inserting an item {100} at the specified index(1st row, 2nd col):
[[ 2 4 1]
 [ 8 7 100]
 [ 10 9 5]]

Difference between != and is not operator in Python

In this tutorial, let us look at the difference between != and is not operator in Python.

!= is defined in Python as the not equal to operator. If the operands on either side are not equal, it returns True; otherwise, it returns False.

The is not operator checks whether the id() of two objects is the same or not. If they are the same, it returns False; otherwise, it returns True. And the is not operator returns True if the operands on either side are not equal, and False if they are.

Difference between != and is not operator in Python

Method #1: Using is not Operator on Numbers

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Check if both the given numbers are equal or not using the is not operator.
  • Print the id of both the given numbers using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_num1 = 5
# Give the second number as static input and store it in another variable.
gvn_num2 = 5

# Check if both the given numbers are equal or not using the is not operator
print(gvn_num1 is not gvn_num2)
# Print the id of both the given numbers using the id() function
print(id(gvn_num1), id(gvn_num2))

Output:

False
11256192 11256192

Explanation:

Here it returns the output as False since both variables
gvn_num1 and gvn_num2 referred to the same data 5

Method #2: Using is not Operator on Strings

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if both the given strings are equal using the is not operator.
  • Print the id of both the given strings using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_str1 = "pythonprogarms"
# Give the second string as static input and store it in another variable.
gvn_str2 = "pythonprogarms"

# Check if both the given strings are equal using the is not operator
print(gvn_str1 is not gvn_str2)
# Print the id of both the given strings using the id() function
print(id(gvn_str1), id(gvn_str2))

Output:

False
140627397413232 140627397413232

Explanation:

Here it returns the output as False since both the string variables
gvn_str1 and gvn_str2 referred to the same data "pythonprogarms"

Method #3: Using is not Operator on Lists

# Give the first list as static input and store it in a variable.
gvn_lst1 = [10, 15, 20]
# Give the second list as static input and store it in another variable.
gvn_lst2 = [10, 15, 20]

# Check if both the given lists are equal using the is not operator
print(gvn_lst1 is not gvn_lst2)
# Print the id of both the given lists using the id() function
print(id(gvn_lst1), id(gvn_lst2))

Output:

True
140627403656880 140627397425344

Explanation:

Here it returns the output as True since both the variables
gvn_lst1 and gvn_lst2 have distinct memory addresses even if 
both variables contain the same data.

Method #4: Using != Operators on Numbers

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Check if both the given numbers are equal or not using the != operator.
  • Print the id of both the given numbers using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_num1 = 5
# Give the second number as static input and store it in another variable.
gvn_num2 = 5

# Check if both the given numbers are equal or not using the != operator
print(gvn_num1 != gvn_num2)
# Print the id of both the given numbers using the id() function
print(id(gvn_num1), id(gvn_num2))

Output:

False
11256192 11256192

Method #5: Using != Operators on Strings

Approach:

  • Give the first string as static input and store it in a variable.
  • Give the second string as static input and store it in another variable.
  • Check if both the given strings are equal or not using the != operator.
  • Print the id of both the given strings using the id() function.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable.
gvn_str1 = "pythonprogarms"
# Give the second string as static input and store it in another variable.
gvn_str2 = "pythonprogarms"

# Check if both the given strings are equal or not using the != operator
print(gvn_str1 !=  gvn_str2)
# Print the id of both the given strings using the id() function
print(id(gvn_str1), id(gvn_str2))

Output:

False
140627397413232 140627397413232

Method #6: Using != Operators on Lists

# Give the first list as static input and store it in a variable.
gvn_lst1 = [10, 15, 20]
# Give the second list as static input and store it in another variable.
gvn_lst2 = [10, 15, 20]

# Check if both the given lists are equal or not using the !=  operator
print(gvn_lst1 != gvn_lst2)
# Print the id of both the given lists using the id() function
print(id(gvn_lst1), id(gvn_lst2))

Output:

False
140627397115488 140627397114768

Method #7: Comparing != and is not operators

gvn_lst1 = []
gvn_lst2 = []
gvn_lst3 = gvn_lst1

# Applying != operator for comparing gvn_lst1 and gvn_lst2
if (gvn_lst1 != gvn_lst2):
    print("True")
else:
    print("False")
 
# Applying is not operator for comparing gvn_lst1 and gvn_lst2
if (gvn_lst1 is not gvn_lst2):
    print("True")
else:
    print("False")
    
# Applying is not operator for comparing gvn_lst1 and gvn_lst3
if (gvn_lst1 is not gvn_lst3):
    print("True")
else:
    print("False")

# Concatenating given third and secondlists and saving it as a given third list
gvn_lst3 = gvn_lst3 + gvn_lst2

# Applying is not operator for comparing gvn_lst1 and gvn_lst3
if (gvn_lst1 is not gvn_lst3):
    print("True")
else:
    print("False")

Output:

False
True
False
True

Explanation:

  • Because both gvn_lst1 and gvn_lst2 are empty lists, the output of the first condition is “False”.
  • Second, if the condition is “True,” it means that two empty lists are located in different memory locations. As a result, gvn_lst1 and gvn_lst2 correspond to distinct items. We can test it using Python’s id() function, which returns an object’s “identity.”
  • If the condition is “False,” the output of the third is “False,” because both gvn_lst1 and gvn_lst3 point to the same object.
  • Since the concatenation of two lists always produces a new list, the output of the fourth if the condition is “True.”

How to Make a Terminal Progress Bar using tqdm in Python

Whenever we install a Python library, module, or software, we see a progress bar appear on the screen, which denotes a small progress bar that estimates how long the process will take to complete or render. It gives the impression of activity and can help to relax us. We’ve all seen the various progress bars.

The percentage of progress made in completing a task is represented by progress bars. The progress can be calculated by dividing the number of items processed by the total number of input items. Several factors influence the progress bar, including network speed, latency, and whether or not data is persisting into local storage to provide a more accurate ETA (Estimated Time of Arrival).

Using the Python external library tqdm, we can create simple and easy progress bars.

Python tqdm library:

The tqdm is a Python library that provides functions that wrap around the specified iterable and output a smart progress bar.
Python is a popular programming language for performing computationally intensive tasks that take a long time to complete.
The progress of these tasks is indicated by a tqdm progress bar.

The name “tqdm” is derived from the Arabic word “taqadum,” which means “progress.”
The library does support customizable progress bars, but at its core, the code tqdm(iterable) is sufficient to get you started with a smart progress metre displaying the iterable’s progress.

Installation

pip install tqdm

Use of tqdm:

To use tqdm, simply add your code between tqdm() after importing the library into your code. You must ensure that the code you insert between the tqdm() function is iterable or it will not work.

Approach:

  • Import tqdm from tqdm module using the import keyword.
  • Loop till the 7e^5 to make the progress bar using the for loop.
  • The Exit of the Program.

Below is the implementation:

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm

# Loop till the 7e^5 to make the progress bar using the for loop
for k in tqdm(range(int(7e5))):
    pass

Output:

100%|██████████| 700000/700000 [00:00<00:00, 1540207.48it/s]

Parameters of tqdm

1) desc: This is used to specify the description of your progress bar

Syntax:

tqdm (self, iterable, desc= "text")

Example

Approach:

  • Import tqdm from tqdm module using the import keyword.
  • Import sleep from time module using the import keyword.
  • Loop till the 80 by specifying any sample description using the desc argument.
  • Sleep for 1 second using the sleep() function.
  • The Exit of the Program.

Below is the implementation:

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 by specifying any sample description using the desc argument
for i in tqdm(range(0, 80), desc ="PythonProgarms"):
  # Sleep for 1 second using the sleep() function
    sleep(.1)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:08<00:00, 9.75it/s]

2) total: It specifies the total number of expected iterations if not specified already or requires any modification.

Syntax:

tqdm (self, iterable, total= 500)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till 80 by specifying the total number of expected iterations using the total argument
for i in tqdm(range(0, 80), total = 400, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 20%|██ | 80/400 [00:16<01:04, 4.93it/s]

3) disable: If you wish to totally disable the progress bar, use this parameter.

Syntax:

tqdm (self, iterable, disable=True)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and if we set disable as true then it will not display progress bar
for i in tqdm(range(0, 80), disable = True, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)
 
print("The iteration is Success")

Output:

The iteration is Success

4) ncols: It represents the total width of the output message. If left unspecified, it defaults to the size of the window. The ncols parameter can be used to fix this.

Syntax:

tqdm (self, iterable, ncols= 100)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and here specify the width of output message using the ncols argument
for i in tqdm(range(0, 80), ncols = 70, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|█████████████████| 80/80 [00:16<00:00, 4.94it/s]

5) mininterval: Using this parameter, we can easily modify the minimum progress display update. The default value is 0.1 seconds.

Syntax:

tqdm (self, iterable, mininterval=3)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and min interval shows the minimum progress display update
for i in tqdm(range(0, 80), mininterval = 4, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:16<00:00, 4.99it/s]

6) ascii: ASCII characters can be used to fill the progress bar of your choice.

Syntax:

tqdm (self, iterable, ascii= "123456789$", desc="text")

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and we filled the progress bar with the ascii characters
for i in tqdm(range(0, 80), ascii ="123456789$"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)
Output:
100%|$$$$$$$$$$| 80/80 [00:16<00:00, 4.95it/s]

7) unit: The default unit of time is “it,” which can be changed to your preferred unit by using this argument.

Syntax:

tqdm (self, iterable, unit= "ticks")

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and here if we specify unit as ticks we get number of ticks per second
for i in tqdm(range(0, 80), unit =" ticks", desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100%|██████████| 80/80 [00:16<00:00, 4.94 ticks/s]

8) initial: The progress bar’s initial value is set to 0. If you want to change this, you may use this argument to set the progress bar to any value you want.

Syntax:

tqdm (self, iterable, initial=50)

Example

# Import tqdm from tqdm module using the import keyword
from tqdm import tqdm
# Import sleep from time module using the import keyword
from time import sleep

# Loop till the 80 and if we specify initial argument then it will be the starting value of the progress bar
for i in tqdm(range(0, 80), initial = 20, desc ="PythonProgarms"):
    # Sleep for 2 seconds using the sleep() function
    sleep(.2)

Output:

PythonProgarms: 100it [00:16, 4.95it/s]

How to get synonyms/antonyms from NLTK WordNet in Python?

The NLTK Wordnet can be used to find word synonyms and antonyms. To comprehend the lexical semantics of the terms in the document, the NLTK Corpus package is used to read the corpus.

WordNet is a big English lexical database. The nouns, verbs, adjectives, and adverbs are grouped into some set of cognitive synonyms, which are called Synsets. Synsets are linked together by conceptual-semantic and lexical relationships.

A WordNet is a lexical database that contains semantic relationships between words and their meanings. WordNet semantic relations include hypernyms, synonyms, holonyms, hyponyms, and meronyms. The NLTK WordNet allows the use of synsets to find words inside the WordNet together with their usages, meanings, and examples. The goal of NLTK WordNet is to find representations between senses. With lexical semantics, relationship type detection is connected to WordNet. A dog can be a mammal, as represented by a “IS-A” relationship type sentence.

Thus, NLTK Wordnet is used to identify relationships between words in a document, as well as spam detection, duplication detection, and characteristics of words inside a written text based on their POS Tags.

The structure of WordNet makes it an excellent tool for computational linguistics and natural language processing.

  • WordNet appears to be similar to a thesaurus in that it puts words together depending on their meanings. There are, however, some key distinctions.
  • First, WordNet connects not just word forms (strings of letters), but also precise senses of words. As a result, words in the network that are close to one another are semantically disambiguate.
  • Second, WordNet labels the semantic relationships between words, whereas thesaurus word groupings do not follow any defined pattern other than meaning similarity.

Python Program to get synonyms/antonyms from NLTK WordNet

Follow the below steps to execute the methods.

Steps:

pip install nltk

Output:

Collecting nltk
Downloading nltk-3.7-py3-none-any.whl (1.5 MB)
---------------------------------------- 1.5/1.5 MB 1.8 MB/s eta 0:00:00
Collecting regex>=2021.8.3
Downloading regex-2022.8.17-cp310-cp310-win_amd64.whl (263 kB)
---------------------------------------- 263.0/263.0 kB 2.7 MB/s eta 0:00:00
Collecting joblib
Downloading joblib-1.1.0-py2.py3-none-any.whl (306 kB)
---------------------------------------- 307.0/307.0 kB 4.7 MB/s eta 0:00:00
Collecting tqdm
Downloading tqdm-4.64.0-py2.py3-none-any.whl (78 kB)
---------------------------------------- 78.4/78.4 kB 2.2 MB/s eta 0:00:00
Requirement already satisfied: click in c:\users\cirus\appdata\local\programs\python\python310\lib\site-packages (from nltk) (8.1.2)
Requirement already satisfied: colorama in c:\users\cirus\appdata\local\programs\python\python310\lib\site-packages (from click->nltk) (0.4.4)
Installing collected packages: tqdm, regex, joblib, nltk

Successfully installed joblib-1.1.0 nltk-3.7 regex-2022.8.17

2)downloading wordnet and omw-1.4

import nltk.corpus
nltk.download('wordnet')

Output:

[nltk_data] Downloading package wordnet to /root/nltk_data...
True
nltk.download('omw-1.4')

Output:

[nltk_data] Downloading package omw-1.4 to /root/nltk_data...
True

Method #1: Getting the definition,type and examples of the word

Approach:

  • Import wordnet from corpus of nltk module using the import keyword.
  • Pass the word to find synsets to the synsets() function.
  • Print the example, and type of the word using the name() function.
  • Print just the word.
  • Print the definition of the word using the definition() function.
  • Print the sample sentences where the word is used using the examples() function.
  • The Exit of the Program.

Below is the implementation:

# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet

# Pass the word to find synsets like so:
synsetsofWord = wordnet.synsets("Price")

# Printing the example,type of the word using the name() function
print('Word and type of the word {price}',synsetsofWord[0].name())

# Printing just the word
print('Printing the word',synsetsofWord[0].lemmas()[0].name())

# Printing the definition of the word using the definition() function
print('Definition of the word:',synsetsofWord[0].definition())

# Printing the sample sentences where the word is used using the examples() function
print('Example sentences where the word is used:',synsetsofWord[0].examples())

Output:

Word and type of the word {price} monetary_value.n.01
Printing the word monetary_value
Definition of the word: the property of having material worth (often indicated by the amount of money something would bring if sold)
Example sentences where the word is used: ['the fluctuating monetary value of gold and silver', 'he puts a high price on his services', "he couldn't calculate the cost of the collection"]

Method #2: Getting the synonyms and antonyms list of the word

Approach:

  • Import nltk module using the import keyword
  • Import wordnet from corpus of nltk module using the import keyword
  • Create an empty list to store the synonyms
  • Create an empty list to store the antonyms
  • Loop in the synsets of the word using the for loop
  • Loop in the above using another nested for loop
  • Add the synonym of the word to the synonyms list using the append() function
  • Add the antonyms to the antonyms list.
  • Print all the unique synonyms from the above resultant synonyms list using the set() function.
  • Print all the unique antonyms from the above resultant antonyms list using the set() function.
  • The Exit of the Program.

Below is the implementation:

# Import nltk module using the import keyword
import nltk
# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet
# Create an empty list to store the synonyms
synonyms_lst = []
# Create an empty list to store the antonyms
antonyms_lst = []

# Loop in the synsets of the word using the for loop
for syn in wordnet.synsets("good"):
  # Loop in the above  using another nested for loop
    for l in syn.lemmas():
        # Add the synonym of the word to the synonyms list using the append() function
        synonyms_lst.append(l.name())
        # Adding the antonyms to the antonyms list
        if l.antonyms():
            antonyms_lst.append(l.antonyms()[0].name())

# Print all the unique synonyms from the above resultant synonyms list
# using the set() function
print('The synonyms of the word {good}',set(synonyms_lst))
# Print all the unique antonyms from the above resultant antonyms list
# using the set() function
print('The antonyms of the word {good}',set(antonyms_lst))

Output:

The synonyms of the word {good} {'in_force', 'undecomposed', 'safe', 'well', 'trade_good', 'proficient', 'unspoilt', 'effective', 'ripe', 'just', 'dependable', 'good', 'expert', 'sound', 'thoroughly', 'beneficial', 'skillful', 'salutary', 'honest', 'right', 'respectable', 'estimable', 'in_effect', 'secure', 'unspoiled', 'upright', 'full', 'dear', 'serious', 'commodity', 'skilful', 'near', 'goodness', 'adept', 'honorable', 'practiced', 'soundly'}
The antonyms of the word {good} {'evilness', 'bad', 'evil', 'badness', 'ill'}

Method #3: Comparing the Similarity Index of Two Words

Below is the implementation:

# Import nltk module using the import keyword
import nltk
# Import wordnet from corpus of nltk module using the import keyword
from nltk.corpus import wordnet

# Pass any two random words as an argument to the synset() function of wordnet to
# find similarity of the both the words and store them in two separate variables
# Here v represents the tag verb
word_1 = wordnet.synset('price.v.01') 
word_2 = wordnet.synset('run.v.01')
# Printing the similarity of the both the words passed using the wup_similarity() function
print(word_1.wup_similarity(word_2))

Output:

0.2857142857142857

How to Download Instagram profile pic using Python

In this post, let us look at how to download Instagram profile pictures using python.

Everyone nowadays utilizes social media, and one of the most popular apps is Instagram. Its users enjoy its material, which includes text, effects, stickers, and so on. One of them is the video and reel feature.

Web scraping is a task that needs an understanding of how web pages are structured. To obtain the required information from web pages, one must first understand the structure of the web pages, then analyze the tags that contain the required information, and finally the attributes of those tags.

It is intended for programmers, data analysts, scientists, and engineers who are already proficient in extracting content from web pages with BeautifulSoup.

You may have noticed that there are numerous websites that are both complex and lengthy, making it difficult to find anything. Python includes some built-in libraries to help us with searching, modifying, and iterating, such as Requests, Xml, Beautiful Soup, Selenium, Scrapy, and so on.

Python Requests

To understand how the requests module works, you must first understand what happens when you browse the web and how it instantaneously displays the data we were hoping to see.

When you click a link, we make an HTTP (Hypertext Transfer Protocol) request to the server that hosts the requested page.

When the server receives the request, it returns the requested content to us.

The two most useful HTTP requests are GET and POST.

Python Code to Download Instagram profile pic

Method #1: Using instaloader Module

Python and the PyCharm IDE must be installed on your computer (or you can use any of your IDE)

We can use the instaloader module to download the profile picture of any Instagram account by simply entering the user’s Instagram handle.

Type the below command to install the instaloader module:

pip install instaloader

Output:

Looking in indexes: 
Collecting instaloader Downloading 
instaloader-4.9.3.tar.gz (60 kB) |████████████████████████████████| 60 
kB 2.7 MB/s Requirement already satisfied: requests>=2.4 in /usr/local/lib/
python3.7/dist-packages (from instaloader) (2.23.0) Requirement already 
satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages 
(from requests>=2.4->instaloader) (3.0.4) Requirement already satisfied: 
idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages 
(from requests>=2.4->instaloader) (2.10) Requirement already satisfied:
urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/
dist-packages (from requests>=2.4->instaloader) (1.24.3) Requirement 
already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/
dist-packages (from requests>=2.4->instaloader) (2022.6.15) 
Building wheels for collected packages: instaloader Building wheel for
instaloader (setup.py) ... done Created wheel for instaloader: 
filename=instaloader-4.9.3-py3-none-any.whl size=62303 
sha256=eaecaa74aa9702c5841e4f698afa7e357a59823c20816bb5dfad4f7193ec40a6 
Stored in directory: /root/.cache/pip/wheels/38/d0/76/393aa35939
4d16f2744f5bf8cb71cddb68ad8944de7722a4bd Successfully built 
instaloader Installing collected packages: instaloader Successfully 
installed instaloader-4.9.3

Approach:

  • Import instaloader module using the import keyword
  • Give the instagram user name as user input using the input() function and store it in a variable
  • Download the instagram profile picture using the download_profile() function by passing the above insta username, profile_pic_only as True as arguments to it.
  • Print some random text for acknowledgment.
  • The Exit of the Program.

Below is the implementation:

# Import instaloader module using the import keyword
import instaloader
# Give the insta user name as user input using the input() function and 
# store it in a variable
instagramUsername = input("Enter some random instagram username = ")
# Download the instagram profile picture using the download_profile() function
# by passing the above insta username, profile_pic_only as True as arguments to it
instaloader.Instaloader().download_profile(instagramUsername , profile_pic_only=True)
# Print some random text for acknowledgment
print("The instagram profile picture is download succesfully!!")

Output:

The instagram profile picture is download succesfully!!

Method #2: Using BeautifulSoup Module

Beautiful Soup, out of all the available Python libraries, is the one that performs web scraping relatively faster than the others. There are times when we need to use Beautiful Soup to find all of the children of a certain element.

Approach:

  • Import requests, BeautifulSoup, json, random and os.path modules using the import keyword.
  • Give the website URL of instagram and store it in a variable.
  • Give the instagram username as user input using the input() function and store it in another variable.
  • Get the response using the requests module get() function.
  • Check if the response is success(here ok attribute specifies request is success).
  • Get the text of the response using the text attribute and save it in a variable.
  • Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension).
  • Check if the above file exists in our system using the isfile() function.
  • If the file doesn’t exists then we can save with the above filename.
  • Open the above file in the write binary mode.
  • Get the response from the string url using the requests module get() function.
  • If we get in any error then we print the error.
  • Else we write the image to the file using the write() function.
  • The Exit of the Program.

Below is the implementation:

# Import requests, BeautifulSoup, json, random and 
# os.path modules using the import keyword
import requests
from bs4 import BeautifulSoup as bs
import json
import random
import os.path

# Give the website URL of instagram and store it in a variable
instagramUrl='https://www.instagram.com'

# Give the insta username as user input using the input() function and 
# store it in another variable
instagramUsername= input("Enter some random instagram username =")

# Get the response using the requests module get() function
response = requests.get(f"{instagramUrl}/{instagramUsername}/")

# Check if the response is success(here ok attribute specifies request is success)
if response.ok:
    # Get the text of the response using the text attribute and save in a variable
    html=response.text
    bs_html=bs(html, features="lxml")
    bs_html=bs_html.text
    index=bs_html.find('profile_pic_url_hd')+21
    remaining_text=bs_html[index:]
    remaining_text_index=remaining_text.find('requested_by_viewer')-3
    string_url=remaining_text[:remaining_text_index].replace("\\u0026","&")

    print(string_url, "\n \n downloading..........")

while True:
    # Create a random file name to store using the random function and save it in a variable (here .jpg specifies image extension)
    filename='pic'+str(random.randint(1, 100000))+'.jpg'
    # Check if the above file exists in our system using the isfile() function
    file_exists = os.path.isfile(filename)
    # If the file doesn't exists then we can save with the above filename
    if not file_exists:
        # Open the above file in the write binary mode
        with open(filename, 'wb+') as handle:
            # Get the response from the string url using the requests module get() function
            response = requests.get(string_url, stream=True)
            # If we get in any error then we print the error
            if not response.ok:
                print(response)
            # Else we write the image to the file using the write() function
            for block in response.iter_content(1024):
                if not block:
                    break
                handle.write(block)
    else:
        continue
    break
print("The instagram profile picture is download succesfully!!")

Output:

Enter some random instagram username = virat.kohli
The instagram profile picture is download succesfully!!

Image:

insta profile photo downloader

Python String split()

The split() method in python splits a string into a list based on the specified separator. The separator can be specified, however, the default separator is any whitespace.

Syntax:

string.split(separator, maxsplit)

Parameters

  • separator: This is optional. The separator to be used when separating the string. By default, any whitespace serves as a separator.
  • maxsplit: This is optional. It represents the number of splits to perform. The default value is -1, which represents “all occurrences.”

Return Value:

A list of strings is returned by the split() method

NOTE

When maxsplit is specified, the list will have the number of elements
specified plus one.

Python String split()

Method #1: Using split() Function (Static Input)

Approach:

  • Give the first string as static input and store it in a variable
  • Apply split() function on the given first string and print the result.
  • Here it splits the string based on the white spaces as there is no separator argument passed.
  • Give the second string as static input and store it in another variable
  • Apply split() function on the given second string by passing the separator as an argument to it and print the result.
  • Here it splits the string based in the ‘@’ symbol
  • Similarly split based on other separators and print the result.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable
gvnstring_1 = 'Hello this is pythonprograms'

# Apply split() fuction on the given first string and print the result. 
# Here it splits the string based on the white spaces as there 
# is no separator argument passed.
print("Splitting gvnstring_1 based on spaces:", gvnstring_1.split())

# Give the second string as static input and store it in another variable
gvnstring_2 = '[email protected]@pythonprograms'

# Apply split() function on the given second string by 
# passing the separator as an argument to it and print the result. 
# Here it splits the string based in the '@' symbol
print("Splitting gvnstring_2 based on '@' symbol:", gvnstring_2.split('@'))

# Similary split based on other separators
gvnstring_3 = 'Welcome:to:pythonprograms'
print("Splitting gvnstring_3 based on ':' symbol:", gvnstring_3.split(':'))

Output:

Splitting gvnstring_1 based on spaces: ['Hello', 'this', 'is', 'pythonprograms']
Splitting gvnstring_2 based on '@' symbol: ['Welcome', 'to', 'pythonprograms']
Splitting gvnstring_3 based on ':' symbol: ['Welcome', 'to', 'pythonprograms']

Method #2: When maxsplit argument is passed (Static Input)

Approach:

  • Give the first string as static input and store it in a variable
  • Apply split() fuction on the given first string by passing space, maxsplit = 0 as arguments to it and print the result.
  • Here it splits the string based on the white spaces but max split is given as 0. So it doesn’t split.
  • Give the second string as static input and store it in another variable
  • Apply split() fuction on the given second string by passing the separator as ‘@’ and maxsplit = 2 as arguments to it and print the result.
  • Here 2 specifies we are going to split two times if the @ symbol is present.
  • Similarly split based on other separators.
  • The Exit of the Program.

Below is the implementation:

# Give the first string as static input and store it in a variable
gvnstring_1 = 'Hello this is btechgeeks'

# Apply split() fuction on the given first string by passing space,
# maxsplit = 0 as arguments to it and print the result. 
# Here it splits the string based on the white spaces but max split is given as 0 
# So it doesn't split
print("Splitting gvnstring_1 based on spaces and maxsplit = 0:")
print(gvnstring_1.split(' ', 0))

# Give the second string as static input and store it in another variable
gvnstring_2 = 'Welcome [email protected]'

# Apply split() fuction on the given second string by passing the separator as '@' and 
# maxsplit = 2 as arguments to it and print the result. 
# Here 2 specifies we are going to split two times if the @ symbol is present
print("Splitting gvnstring_2 based on '@' symbol and maxsplit = 2:")
print(gvnstring_2.split('@', 2))

# Similary split based on other separators
gvnstring_3 = 'Welcome:to:btechgeeks'
print("Splitting gvnstring_3 based on ':' symbol and maxsplit = 1:")
print(gvnstring_3.split(':', 1))

Output:

Splitting gvnstring_1 based on spaces and maxsplit = 0:
['Hello this is btechgeeks']
Splitting gvnstring_2 based on '@' symbol and maxsplit = 2:
['Welcome to', 'btechgeeks']
Splitting gvnstring_3 based on ':' symbol and maxsplit = 1:
['Welcome', 'to:btechgeeks']

Method #3: Using split() Functions (User Input)

Approach:

  • Give the first string as user input using the input() function and store it in a variable.
  • Give the second string as user input using the input() function and store it in another variable.
  • Apply split() function on the given string by passing the given separator as an argument to it and print the result.
  • Here it splits the string based in the given separator.
  • The Exit of the Program.

Below is the implementation:

# Give the string as user input using the input() function 
# and store it in a variable
gvn_str = input("Enter some random string = ")

# Give the string as user input using the input() function 
# and store it in another variable
gvn_separator = input("Enter some random separator = ")

# Apply split() function on the given string by passing the given separator 
# as an argument to it and print the result. 
# Here it splits the string based in the given separator 
print("Splitting the given string {",gvn_str,"} based on the given separator{",gvn_separator,"}:")
print(gvn_str.split(gvn_separator))

Output:

Enter some random string = hello&this&is&btechgeeks
Enter some random separator = &
Splitting the given string { hello&this&is&btechgeeks } based on the given separator{ & }:
['hello', 'this', 'is', 'btechgeeks']

Method #4: When maxsplit argument is passed (User Input)

# Give the string as user input using the input() function and store it in a variable
gvn_string= 'Hello#this#is#pythonprograms'

# Give the separator value as user input using the input() function 
# and store it in another variable
gvn_separator = input("Give some random separator = ")

# Give the maxsplit value as user input using the int(), input() function 
# and store it in another variable
gvn_maxsplit = int(input("Give some random maxsplit value = "))

# Apply split() function on the given string by passing the given separator 
# and maxsplit values as arguments to it to split the string based on the
# given separator and maxsplit values
print("Splitting the given string based on", gvn_separator,"and maxsplit =",gvn_maxsplit,":")
print(gvn_string.split(gvn_separator, gvn_maxsplit))

Output:

Give some random separator = #
Give some random maxsplit value = 2
Splitting the given string based on # and maxsplit = 2 :
['Hello', 'this', 'is#pythonprograms']