What is the numpy.char.endswith() function from NumPy in Python?

Overview

The char.endswith() function in Python is returns a Boolean array which is True where the string elements in a given array a ends with a suffix. Otherwise, it's false.

Syntax

char.endswith(a, suffix, start=0, end=None)
Syntax for the char.endswith() function

Parameter value

The char.endswith() function takes the following parameter values:

  • a: This is the input array.
  • suffix: This is the character string from the input array to be checked for.
  • start: With an optional start, the test to test begins at that position.
  • end: With an optional end, the comparison stops at the given position.

Return value

The char.endswith() function returns an output array having Boolean values.

Example

import numpy as np
# creating an input array
a = np.array(["Hello", "Red", "Goat", "Tired"])
# implementing the char.endwith() function to check if the elements ends with "ed"
myarray = np.char.endswith(a, "ed", start=1, end=3 )
# printing the result
print(myarray)

Explanation

  • Line 1: We import the numpy module.
  • Line 3: We create an input array a using the array() function.
  • Line 6: We use the char.endswith() function to check if the string character ed appears in each element of the input array a. We start from the second character (index 1)to the third character (index 2) of each element. We assign the result to a variable, myarray.
  • Line 9: We print the variable myarray.

Free Resources