Numpy char.strip() Function



The Numpy char.strip() function is used to remove leading and trailing whitespace characters from each string element in an array. This function is useful for cleaning and preprocessing text data to ensure consistent formatting.

This function can also remove specified characters by providing them as an argument. It processes each string in the input array individually and returns an array of the same shape with the leading and trailing characters removed.

Syntax

Following is the syntax of Numpy char.strip() function −

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

Parameters

Following are the parameters of Numpy char.strip() function −

  • a(array-like of str or unicode): The input array containing strings.

  • chars(str, optional): This parameter is a string of characters to be removed. If not specified then whitespace characters are removed.

Return Value

This function returns an array with the same shape as the input with leading and trailing characters removed.

Example 1

Following is the basic example of Numpy char.strip() function. Here in this example we are removing the leading and trailing whitespace from each string element in a NumPy array −

import numpy as np

arr = np.array(['  hello  ', '  world  ', '  numpy  '])
stripped_arr = np.char.strip(arr)
print(stripped_arr)

Below is the output of the basic example of numpy.char.strip() function −

['hello' 'world' 'numpy']

Example 2

We can use the char.strip() function to remove both whitespace and specified characters from the beginning and end of each string element in a NumPy array. This is particularly useful when we need to clean strings that may contain unwanted characters and spaces. Below is the example of it −

import numpy as np

arr = np.array(['  **hello**  ', '  !!world!!  ', '  %%numpy%%  '])
stripped_arr = np.char.strip(arr, chars=' *!%')
print(stripped_arr)

Here is the output of including newline characters −

['hello' 'world' 'numpy']

Example 3

The char.strip() function is versatile and can be used to remove not just whitespace but any specified characters from the beginning and end of each string. Following example shows how to remove the specified characters −

import numpy as np

arr = np.array(['--hello--', '==world==', '++numpy++'])
stripped_arr = np.char.strip(arr, chars='-=+')
print(stripped_arr)

Here is the output of limiting the number of strips −

['hello' 'world' 'numpy']
numpy_string_functions.htm
Advertisements