NumPy strings.strip()

The numpy.strings.strip() function removes leading and trailing characters from each element in an array-like structure. By default, it removes whitespace, but a custom set of characters can be specified.

Syntax

</>
Copy
numpy.strings.strip(a, chars=None)

Parameters

ParameterTypeDescription
aarray-like, with StringDType, bytes_, or str_ dtypeThe input array containing strings to be stripped.
charsscalar with the same dtype as a, optionalSpecifies the set of characters to be removed. If None, it removes whitespace.

Return Value

Returns an ndarray of the same type as the input, with leading and trailing characters removed based on the specified chars argument.


Examples

1. Stripping Whitespace from Strings

By default, strings.strip() removes whitespace from the beginning and end of each string.

</>
Copy
import numpy as np

# Define an array of strings with leading and trailing spaces
fruits = np.array(["  apple  ", "  banana", "cherry   "], dtype="str")

# Strip whitespace from both ends
stripped_fruits = np.strings.strip(fruits)

# Print the results
print("Original:", fruits)
print("Stripped:", stripped_fruits)

Output:

Original: ['  apple  ' '  banana' 'cherry   ']
Stripped: ['apple' 'banana' 'cherry']