learn how to use python string index() with example

The index() method in Python is used to find the first occurrence of a specified value within a string. If the value is found, it returns the lowest index of its occurrence. If the value is not found, it raises a ValueError.

Syntax:

str.index(sub, start, end)

sub: This is the substring you’re looking for. It’s required.

start and end: These are optional arguments that let you specify where to start and end the search within the string. The range includes the start index and excludes the end index.

How to use the index() method:

sentence = "Hello, welcome to the world of Python."
print(sentence.index("Python")) # Outputs: 31

Example 1

We want to find the starting index of the word Python

sentence = "Python is a popular programming language."
print(sentence.index("Python")) # Outputs: 0

Example 2

Using index() with the start and end parameters.

sentence = "Python is a popular programming language."
print(sentence.index("popular", 10)) # Outputs: 12

Example 3

Using index() to find the occurrence of a character.

text = "Look for the first occurrence of 'o'."
print(text.index('o')) # Outputs: 1