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 in a range using Python index()
The numpy.char.index() method returns the lowest index where a substring is found within string arrays. It searches within a specified range and raises ValueError if the substring is not found.
Syntax
numpy.char.index(a, sub, start=0, end=None)
Parameters
The method accepts the following parameters:
- a − Input array of strings
- sub − Substring to search for
- start − Starting position for search (optional)
- end − Ending position for search (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', 'CRATE'])
print("Array:", arr)
# Find index of 'AT' substring
result = np.char.index(arr, 'AT')
print("Index of 'AT':", result)
Array: ['KATIE' 'KATE' 'CRATE'] Index of 'AT': [1 1 2]
Using Start and End Parameters
You can specify a range to search within using start and end parameters −
import numpy as np
arr = np.array(['KATIE', 'KATE', 'CRATE'])
print("Array:", arr)
# Search for 'AT' between positions 1 and 4
result = np.char.index(arr, 'AT', start=1, end=4)
print("Index of 'AT' (range 1-4):", result)
Array: ['KATIE' 'KATE' 'CRATE'] Index of 'AT' (range 1-4): [1 1 2]
How It Works
The method searches each string in the array:
- KATIE − 'AT' found at index 1
- KATE − 'AT' found at index 1
- CRATE − 'AT' found at index 2
Error Handling
The method raises ValueError if the substring is not found −
import numpy as np
arr = np.array(['HELLO', 'WORLD'])
try:
result = np.char.index(arr, 'XYZ')
print(result)
except ValueError as e:
print("Error: Substring not found")
Error: Substring not found
Conclusion
Use numpy.char.index() to find substring positions in string arrays. It returns the lowest index for each string and raises ValueError when substring is not found.
Advertisements
