w3resource

NumPy: Check whether each element of a given array starts with "P"


Write a NumPy program to check whether each element of a given array starts with "P".

Sample Solution:

Python Code:

# Importing necessary library
import numpy as np

# Creating a NumPy array containing strings
x1 = np.array(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str)

# Displaying the content of the original array
print("\nOriginal Array:")
print(x1)

# Checking if each element starts with 'P'
print("Test if each element of the said array starts with 'P':")
r = np.char.startswith(x1, "P")

# Displaying the result
print(r) 

Sample Input:

(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str)

Sample Output:

Original Array:
['Python' 'PHP' 'JS' 'examples' 'html']
Test if each element of the said array starts with 'P':
[ True  True False False False]

Explanation:

In the above exercise –

x1 = np.array(['Python', 'PHP', 'JS', 'examples', 'html'], dtype=np.str): This code creates a NumPy array x1 of string data type (dtype=np.str) containing the values "Python", "PHP", "JS", "examples", and "html".

r = np.char.startswith(x1, "P"): This code applies the np.char.startswith() function to the x1 array with the prefix "P" as the second argument. This function returns a boolean NumPy array r where each element is True if the corresponding element in x1 starts with "P", and False otherwise.

So, the output r will be a boolean NumPy array with the values [True, True, False, False, False], indicating that the first two elements of x1 start with "P", while the rest do not.

Pictorial Presentation:

NumPy String: Check whether each element of a given array starts with 'P'.

Python-Numpy Code Editor: