NumPy strip() function

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 ShishirKant     "  
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:

The Original String:
    welcome to ShishirKant    
After Removing the leading and trailing whitespaces from the string:
welcome to ShishirKant

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([ 'ShishirKant', 'For', 'oo'] ) 
print ("The Input array : ")
print(inp) 

output = np.char.strip(inp, chars ='S') 
print ("The Output array: \n", output) 
The Input array :
['ShishirKant' 'For' 'oo']
The Output array:
['hihirKant' 'For' 'oo']
Follow Us On