Signup/Sign In

NumPy strip() function

In this tutorial, we will cover the strip() function available in the char module of the Numpy library.

The strip() function is used to strip or remove the leading and trailing characters for each element in an array. We can specify the character to be stripped, otherwise by default this function will remove the extra leading and trailing whitespaces from the string.

This function basically calls str.strip in an element-wise manner.

Syntax of numpy.char.strip():

The syntax required to use this function is as follows:

numpy.char.strip(a, chars=None)

The above syntax indicates that strip() function takes two parameters.

Parameters:

Let us now take a look at the parameters of this function:

  • a
    This parameter indicates an array on which the function will be applied.

  • chars
    The chars argument is basically a string that specifies the set of characters to be removed. If this argument is not provided or provided as None, then by default removes the whitespace.

Returned Values:

This function will return an output array of strings with the characters specified in the strip() function removed from the strings.

Example 1:

In the below code snippet we will use strip() function:

import numpy as np   

str = "     welcome to studytonight     "  
print("The Original String:")  
print(str)
print("After Removing the leading and trailing whitespaces from the string :") 
 
a = np.char.strip(str)
print(a)

Output:

Numpy strip() function example

Example 2:

Let's have another example.

import numpy as np

inp = np.array(['Sunday   ', '     Monday ', '  Tues   ']) 
print ("The Input array : ", inp) 

output = np.char.strip(inp) 
print ("The Output array: ", output) 

Output:

Numpy strip() function example

Example 3:

In this example given below, we will strip the character 'S' from the elements of our array and the code snippet for the same is as follows:

import numpy as np

inp = np.array([ 'Studytonight', 'For', 'oo'] ) 
print ("The Input array : ")
print(inp) 

output = np.char.strip(inp, chars ='S') 
print ("The Output array: \n", output) 


The Input array :
['Studytonight' 'For' 'oo']
The Output array:
['tudytonight' 'For' 'oo']

Summary

In this tutorial we learned about strip() function in the Numpy library. We covered how it is used with its syntax and values returned by this function along with a few examples.



About the author:
Aspiring Software developer working as a content writer. I like computer related subjects like Computer Networks, Operating system, CAO, Database, and I am also learning Python.