Skip to main content
Python String index and Find()

Python String index() and Find()

In this tutorial, we will learn about the Python index() method with the help of examples. I also let you know how to do the same thing using find() method.

Python index() Method

The index() method finds the first occurrence of the specified value. It returns the index of a substring inside the string.

If the substring is not found, it raises an exception.

This method is the same as find(), but raises an exception if sub is not found.

Syntax:
str.index(str, beg = 0 end = len(string))

Parameters:

  • str: This specifies the string to be searched.
  • beg: This is the starting index, by default its 0.
  • end: This is the ending index, by default its equal to the length of the string.

Simple Example:

str = 'Pythonpip is a python tutorial'
result = str.index('python')
print(result)
print(str.index('is a', 10, -4))

Output :

15
10

Example 2: index() With No start and end Argument

result is the first occurrence of the letter “a”?:

str = "Pythonpip is a python tutorial."

result = str.index("a")

print(result)

Example 3: index() With start and end Arguments

Search character a between position 3 and 15?:

str = "Pythonpip is a python tutorial."

result = str.index("a", 3, 15)

print(result)

Python Find() Method

The find() method finds the first occurrence of the specified value. This method returns -1 if the value is not found.

Syntax:
string.find(value, start, end)

  • value: This is a value to search for.
  • start: This is the starting index, by default its 0.
  • end: This is the ending index, by default its equal to the length of the string.

Simple Example:

str = 'Pythonpip is a python tutorial'
result = str.find('python')
print(result)
print(str.index('is a', 10, -4))

Output :

15
10

Example 2: find() With No start and end Argument

str = 'Pythonpip is a python tutorial'

# check the index of 'is'
print(str.find('is'))

Example 3: find() With start and end Arguments

str = 'Pythonpip is a python tutorial'

# check the index of 'is'
print(str.find('is', 3, 10))

Leave a Reply

Your email address will not be published. Required fields are marked *