w3resource

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


18. Check if Strings Start 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'.

For more Practice: Solve these Related Problems:

  • Create a function that returns a boolean array indicating whether each string in an array starts with the letter "P" using np.char.startswith.
  • Implement a solution that performs the check in a case-insensitive manner.
  • Test the function on an array of strings with leading spaces to ensure proper trimming before the check.
  • Combine the starting letter check with a count of total characters to filter for strings that start with "P" and exceed a given length.

Go to:


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.

Python-Numpy Code Editor:

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.