w3resource

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

NumPy String: Exercise-18 with Solution

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:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a NumPy program to check whether each element of a given array is composed of digits only, lower case letters only and upper case letters only.
Next: Write a NumPy program to add two zeros to the beginning of each element of a given array of string values.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-string-exercise-18.php