w3resource

NumPy String: numpy.char.index() function

numpy.char.index() function

The numpy.char.index() function returns the lowest index of a substring in a string. If the substring is not found in the string, it raises a ValueError.

The function is useful in data cleaning and manipulation tasks where we need to extract specific parts of a string or verify if a substring exists in a string.

Syntax:

numpy.char.index(a, sub, start=0, end=None)

Parameters:

Name Description Required /
Optional
a: array_like of str or unicode Input an array_like of string or unicode. Required
sub Input string or unicode str or unicode
start, end: int Input integer. Optional

Return value:

out : ndarray - Output array of ints. Returns -1 if sub is not found.

Example: Finding index of a substring in a string using numpy.char.index()

>>> import numpy as np
>>> x = np.char.index('the quick brown fox jumps over the lazy dog', 'over the lazy dog', start=0, end=None)
>>> x
array(26)

In the above example, we have passed the string 'the quick brown fox jumps over the lazy dog' and a substring 'over the lazy dog' to the method, along with the start and end positions for searching. The method returns an array containing the index of the first occurrence of the substring. In this case, the substring is found starting at position 26 in the string, which is returned as an array.

Pictorial Presentation:

NumPy String operation: index() function

Example: Finding index of a substring in a string using numpy.char.index()

>>> import numpy as np
>>> y = np.char.index('w3resource', 'u', start=0, end=None)
>>> y
array(6)

In the above example, the substring 'u' is searched in the string 'w3resource'. Since the substring is present in the string, the function returns the index of the first character of the substring, which is 6.

Pictorial Presentation:

NumPy String operation: index() function

Python - NumPy Code Editor:

Previous: find()
Next: isalpha()



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://www.w3resource.com/numpy/string-operations/index_func.php