Python String index() Method
Last Updated :
07 Nov, 2024
Improve
The index() method in Python is used to find the position of a specified substring within a given string. It is similar to the find() method but raises a ValueError if the substring is not found, while find() returns -1. This can be helpful when we want to ensure that the substring exists in the string before proceeding.
Let’s see a simple use of index():
s = "Python programming"
position = s.index("prog")
print(position)
Output
7
Explanation: index() method searches for the substring “prog” within “Python programming” and returns starting index 7.
Table of Content
Syntax of index()
s.index(substring, start=0, end=len(s))
Parameters:
- substring: The substring to locate within the string s.
- start (optional): The starting index for the search. Defaults to 0 if not provided.
- end (optional): The ending index for the search. If not provided, it defaults to the length of the string.
Return Type:
- Returns the lowest index of the substring if found in the given string.
- Raises a ValueError if the substring is not found in the specified range.
Example of index() Method
Let’s understand the use of index() with the help of some examples.
Using index() with only substring argument
s = "Python programming is powerful"
position = s.index("programming")
print(position)
Output
7
Explanation:
- Here, we only provide the substring argument “programming”.
- index() searches from the start of the string and finds “programming” at index 7, which it returns.
Using index() with substring, start, and end arguments
s = "Python programming is fun"
position = s.index("is", 10, 25)
print(position)
Output
19
Explanation:
- We specify start=10 and end=25, so index() searches between these positions.
- It finds “is” at index 18 within this range and returns 18.
Related Articles: