Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Return the lowest index in the string where substring is found using Python index()
The numpy.char.index() method returns the lowest index where a substring is found within each string element of a NumPy array. It raises a ValueError if the substring is not found in any string.
Syntax
numpy.char.index(a, sub, start=0, end=None)
Parameters
- a − Input array of strings
- sub − Substring to search for
- start − Starting position (optional)
- end − Ending position (optional)
Basic Example
Let's find the index of substring 'AT' in string arrays ?
import numpy as np
# Create array of strings
arr = np.array(['KATIE', 'KATE'])
print("Array:", arr)
# Find index of 'AT' in each string
result = np.char.index(arr, 'AT')
print("Index of 'AT':", result)
Array: ['KATIE' 'KATE'] Index of 'AT': [1 1]
Using Start and End Parameters
You can specify start and end positions to search within a range ?
import numpy as np
# Create array of strings
arr = np.array(['PYTHON', 'PROGRAM'])
print("Array:", arr)
# Find 'O' starting from index 2
result = np.char.index(arr, 'O', start=2)
print("Index of 'O' from position 2:", result)
Array: ['PYTHON' 'PROGRAM'] Index of 'O' from position 2: [4 2]
Error Handling
The method raises ValueError when substring is not found ?
import numpy as np
arr = np.array(['HELLO', 'WORLD'])
try:
result = np.char.index(arr, 'XYZ')
print("Index found:", result)
except ValueError as e:
print("Error:", e)
Error: substring not found
Comparison with find() Method
| Method | When Substring Found | When Not Found |
|---|---|---|
index() |
Returns index position | Raises ValueError |
find() |
Returns index position | Returns -1 |
Conclusion
Use numpy.char.index() to find the first occurrence index of a substring in string arrays. Handle ValueError exceptions when the substring might not exist, or use find() for safer operations.
Advertisements
