Free cookie consent management tool by TermsFeed The startswith() function of numpy.strings module | Pythontic.com

The startswith() function of numpy.strings module

Overview:

  • The numpy.strings.startswith() function checks whether the string elements of an ndarray start with a given prefix. If a string element starts with the given prefix the result is True. The result is False otherwise. The results are returned as an ndarray containing Boolean values. If the input parameter is a string then a single Boolean value is returned.

  • The supported string types are: bytes, _str, StrDType

Example 1 - Finding prefixes in an ndarray:

# Example Python program that finds whether the elements of an ndarray
# start with a given prefix using the numpy.strings function startswith()
import numpy

# Create a NumPy array of unicode strings
stockSymbols = numpy.ndarray(shape = (2, 2), dtype = numpy.dtype('U10'))

stockSymbols[0][0] = "NAS_MSFT"
stockSymbols[0][1] = "NAS_NVDA"
stockSymbols[1][0] = "NAS_AAPL"
stockSymbols[1][1] = "HKG_4335" # Not a NASDAQ symbol

# Mark the NASDAQ symbols with True
prefix = "NAS"
results = numpy.strings.startswith(stockSymbols, prefix)

# Print symbols and their prefix presence
print("Symbols:")
print(stockSymbols)

print("Symbols start with NAS:")
print(results)

Output:

Symbols:

[['NAS_MSFT' 'NAS_NVDA']

 ['NAS_AAPL' 'HKG_4335']]

Symbols start with NAS:

[[ True  True]

 [ True False]]

Example 2 - Finding prefixes in an ndarray using start and stop positions:

# Example Python program that finds prefixes 
# using a start and end index of an ndarray string elements
import numpy

stockSymbols = numpy.ndarray(shape = (2, 3), dtype = numpy.dtype('U10'))

stockSymbols[0][0] = "EXC1_EQY_ABC"
stockSymbols[0][1] = "EXC1_EQY_BCD"
stockSymbols[0][2] = "EXC1_EQY_DEF"

stockSymbols[1][0] = "EXC1_FUT_ABC"
stockSymbols[1][1] = "EXC1_FUT_BCD"
stockSymbols[1][2] = "EXC1_FUT_DEF"

prefix = "EQY"
results = numpy.strings.startswith(stockSymbols, prefix, start=5, end=8)
print("Symbols:")
print(stockSymbols)

print("Symbols belong to equity segment:")
print(results)

Output:

[[ True  True  True]

 [False False False]]

Example 3 - Find prefix on a string parameter:

# Example Python program that checks a Python string for prefix using
# both numpy.strings.startswith() and Python's str.startswith()
import numpy

inputString = "Long long ago there was a..."
prefix         = "Long"

# Using NumPy
result = numpy.strings.startswith(inputString, prefix)
print(result)

# Using Python's str class
result = inputString.startswith(prefix)
print(result)

Output:

True

True

 


Copyright 2025 © pythontic.com