np.char.endswith() method - Python
The np.char.endswith() method is used to check whether each string in a NumPy array ends with a specified substring.
For Example: This example checks whether each string in a 1D array ends with the letter "s".
import numpy as np
arr = np.array(["cats", "dogs", "fish"])
print("Array:", arr)
res = np.char.endswith(arr, "s")
print("Result:", res)
Output
Array: ['cats' 'dogs' 'fish'] Result: [ True True False]
Explanation:
- "cats" and "dogs" end with "s" -> True
- "fish" does not end with "s" -> False
Syntax
np.char.endswith(a, suffix)
Parameters:
- a: array_like of str -> Input array of strings.
- suffix: str -> Substring to check at the end of each string.
Return Value: ndarray of bool -> Boolean array indicating whether each string ends with the given substring.
Examples
Example 1: This example checks if strings in a 1D array end with "ks".
import numpy as np
arr = np.array(['geeks', 'for', 'geeks'])
res = np.char.endswith(arr, 'ks')
print(res)
Output
[ True False True]
Example 2: This example checks if strings in the array end with the digit "1".
import numpy as np
arr = np.array(['item1', 'item2', 'item3', 'product1'])
res = np.char.endswith(arr, '1')
print(res)
Output
[ True False False True]
Example 3: This example shows that the method is case-sensitive.
import numpy as np
arr = np.array(['Apple', 'banana', 'Orange'])
res = np.char.endswith(arr, 'e')
print(res)
Output
[ True False True]