Python String index() method is used to find the first occurrence of a specified substring within a string.
This method is similar to the find() method for strings. The main difference is that while the find() method returns -1 when the substring is not found, the index() method raises a ValueError.
Syntax
string.index(value, start, end)
Parameters
- value(required): It is the substring you are searching for in the original string.
- start(optional): It is the starting index where the search begins. The default is 0.
- end(optional): It is the ending index where the search ends. The default is to the end of the string.
Return value
If a substring exists inside the string, it returns the index of the first occurrence of the substring. If the substring doesn’t exist inside the string, it raises a ValueError exception.
Visual Representation
Example 1: How to Use Python string index() Method
str = 'Expecto Patronum'
extract = str.index('num')
print(extract)
Output
13
Example 2: Passing start and end parameters
str = 'Leo Messi'
sample = str.index('M', 0, 6)
print(sample)
Output
4
Example 3: ValueError: substring not found
str1 = "Hello! This is Krunal"
str2 = "venom"
result = str1.index(str2, 25)
print("The index where the substring is found:", result)
Output
ValueError: substring not found
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.