How to Return a Boolean Array True Where the String Array Ends with Suffix Using NumPy?
In this article, we will discuss how to return a boolean array that is True where the string element in the array ends with a suffix using NumPy in Python.
Example: Check the array ends with Com Input: email@example.com Output: True Input: firstname.lastname@example.org Output: False
In Python, numpy.char module provides a set of vectorized string operations for arrays of type numpy.str_. We can use Numpy.char.endswith method to return a Boolean array which is True where the string element in array ends with suffix.
Syntax: char.endswith(a, suffix, start=0, end=None)
- a: array_like of str or unicode
- suffix: str
- start, end: int, optional
- With optional start, test beginning at that position. With optional end, stop comparing at that position.
- out: ndarray
- Outputs an array of bools.
We have an array of Email addresses, we need to check which of them are valid emails by checking the suffix “.com”. If a string ends with “.com” it should return True otherwise False.
[ True False True]
In the previous example, we have validated the email address with the suffix “.com”, now we will validate the domain of the email address. This time we are interested in the domain “abc” only, not “.com”
The address with domain abc should return True otherwise False. Assume that, there will be exactly 4 characters after the domain(ex: “.com”)
[ True True False]