Python 3 – String index() Method
The Python string index()
method is used to find the first occurrence of a substring in a given string. This method returns the index of the first occurrence of the substring in the string.
Syntax
str.index(sub[, start[, end]])
where:
sub
– This is the substring to be searched in the given string.start
– This is the starting index in the string from where the search begins. By default, it is 0.end
– This is the ending index in the string until where the search is done. By default, it is the end of the string.
Return Value
This method returns the index of the first occurrence of the substring in the string. If the substring is not found, it raises a ValueError
exception.
Example
# Find the index of the first occurrence of a substring
string = "hello world"
substring = "world"
index = string.index(substring)
print(index)
Output:
6
In the above example, the index()
method finds the first occurrence of the substring world
in the string hello world
and returns the index 6
.
Let’s now see another example:
# Using start and end parameters
string = "hello world, how are you doing today?"
substring = "o"
index = string.index(substring, 4, 15)
print(index)
Output:
7
In the above example, the index()
method searches for the first occurrence of the substring o
in the string hello world, how are you doing today?
starting from index 4
and up to index 15
(exclusive). The method returns the index 7
.
If the substring is not in the string, the index()
method raises a ValueError
exception.
# Substring not found
string = "hello world"
substring = "python"
try:
index = string.index(substring)
print(index)
except ValueError:
print(f"The substring '{substring}' is not in the string '{string}'")
Output:
The substring 'python' is not in the string 'hello world'
That’s it for the Python string index()
method.
Conclusion
In this article, we have seen how to use the Python string index()
method to find the index of the first occurrence of a substring in a given string. Remember that if the substring is not found, the method raises a ValueError
exception, so you should always use a try-except
block to handle it.