NumPy strings.rstrip()
The numpy.strings.rstrip()
function removes trailing characters from each element in an array of strings. If no specific characters are provided, it removes whitespace by default.
Syntax
</>
Copy
numpy.strings.rstrip(a, chars=None)
Parameters
Parameter | Type | Description |
---|---|---|
a | array-like, with StringDType, bytes_, or str_ dtype | An array of strings where trailing characters will be removed. |
chars | scalar with the same dtype as a , optional | Specifies a set of characters to be removed from the end of each string. If None , it removes whitespace. |
Return Value
Returns an array where trailing characters have been removed from each string. The output array retains the same data type as the input.
Examples
1. Removing Trailing Whitespace
This example removes trailing spaces from a list of fruit names.
</>
Copy
import numpy as np
# Define an array of strings with trailing spaces
fruits = np.array([" apple ", " banana ", "cherry "], dtype="U")
# Remove trailing spaces
result = np.strings.rstrip(fruits)
# Print the result
print("Original:", fruits)
print("Stripped:", result)
Output:
Original: [' apple ' ' banana ' 'cherry ']
Stripped: [' apple' ' banana' 'cherry']

2. Removing Specific Trailing Characters
Here, we remove specific trailing characters from fruit names.
</>
Copy
import numpy as np
# Define an array of strings with unwanted trailing characters
fruits = np.array(["apple!!", "banana??", "cherry!!"], dtype="U")
# Remove '!' and '?' from the end of each string
result = np.strings.rstrip(fruits, chars="!?")
# Print the result
print("Original:", fruits)
print("Stripped:", result)
Output:
Original: ['apple!!' 'banana??' 'cherry!!']
Stripped: ['apple' 'banana' 'cherry']

3. Removing Multiple Characters at Once
This example removes multiple trailing characters from fruit names.
</>
Copy
import numpy as np
# Define an array of strings with mixed trailing characters
fruits = np.array(["apple###", "banana$$$", "cherry!!##"], dtype="U")
# Remove multiple characters ('#', '$', '!')
result = np.strings.rstrip(fruits, chars="#$!")
# Print the result
print("Original:", fruits)
print("Stripped:", result)
Output:
Original: ['apple###' 'banana$$$' 'cherry!!##']
Stripped: ['apple' 'banana' 'cherry']

4. Removing Digits from the End
In this example, we remove trailing digits from fruit names.
</>
Copy
import numpy as np
# Define an array of strings with trailing numbers
fruits = np.array(["apple123", "banana456", "cherry789"], dtype="U")
# Remove trailing digits
result = np.strings.rstrip(fruits, chars="0123456789")
# Print the result
print("Original:", fruits)
print("Stripped:", result)
Output:
Original: ['apple123' 'banana456' 'cherry789']
Stripped: ['apple' 'banana' 'cherry']
