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
Parameter | Type | Description |
---|---|---|
a | array-like, with StringDType , bytes_ , or str_ dtype | The input array containing strings to be stripped. |
chars | scalar with the same dtype as a , optional | Specifies 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']

2. Stripping Specific Characters
You can specify a set of characters to remove instead of whitespace.
</>
Copy
import numpy as np
# Define an array of strings with extra characters
fruits = np.array(["--apple--", "**banana**", "!!cherry!!"], dtype="str")
# Strip specified characters
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']

3. Stripping Numbers from Strings
The function removes any combination of characters specified, not just prefixes or suffixes.
</>
Copy
import numpy as np
# Define an array of strings with numbers at different positions
fruits = np.array(["123apple321", "456banana789", "000cherry000"], dtype="str")
# Strip numbers from both ends
stripped_fruits = np.strings.strip(fruits, "0123456789")
# Print the results
print("Original:", fruits)
print("Stripped:", stripped_fruits)
Output:
Original: ['123apple321' '456banana789' '000cherry000']
Stripped: ['apple' 'banana' 'cherry']

4. Stripping Mixed Characters
Combining various characters like spaces, special characters, and numbers to remove from strings.
</>
Copy
import numpy as np
# Define an array of strings with mixed unwanted characters
fruits = np.array([" *123apple321* ", "**banana!@#", "000 cherry 000"], dtype="str")
# Strip spaces, numbers, and special characters
stripped_fruits = np.strings.strip(fruits, " *0123456789!@#")
# Print the results
print("Original:", fruits)
print("Stripped:", stripped_fruits)
Output:
Original: [' *123apple321* ' '**banana!@#' '000 cherry 000']
Stripped: ['apple' 'banana' 'cherry']
