NumPy strings.startswith()
The numpy.strings.startswith() function checks whether each string element in an array starts with a specified prefix. It returns a boolean array indicating which elements start with the given prefix.
Syntax
</>
Copy
numpy.strings.startswith(a, prefix, start=0, end=None)
Parameters
| Parameter | Type | Description |
|---|---|---|
a | array-like (StringDType, bytes_, or str_ dtype) | Input array of strings. |
prefix | array-like (StringDType, bytes_, or str_ dtype) | Prefix to check at the start of each string. |
start | array-like (integer dtype), optional | Specifies the position to start checking within the string. |
end | array-like (integer dtype), optional | Specifies the position to stop checking. |
Return Value
Returns an array of boolean values. Each element is True if the corresponding string starts with the given prefix, otherwise False.
Examples
1. Checking If Strings Start with a Given Prefix
Here, we check whether each string in the array starts with the specified prefix.
</>
Copy
import numpy as np
# Define an array of strings
strings = np.array(["apple", "banana", "apricot", "blueberry"], dtype="U")
# Define the prefix to check
prefix = "ap"
# Check if each string starts with the prefix
result = np.strings.startswith(strings, prefix)
# Print the result
print("Does each string start with 'ap'?:", result)
Output:
Does each string start with 'ap'?: [ True False True False]
