Methods and Functions

Python String index()

There might arise a situation where the user might want to find out the position of a specific data element in the iterable. Assume you have a list of your company’s top 10 employees and want to know where Employee Sam falls on that list. This operation can be performed by using the string handling methods provided by Python. For this issue, the Python index() method is used. Python index() is a string method that helps to identify the first index position of the specified characters from the input string. Let us learn more about the Python index() string function, its syntax along with various program examples.

Python index

Definition

  • Python index() built-in function is used to return the index value of the first occurrence of a substring from the input string if the substring is found. If the substring specified is not found, then it raises an exception.
  • The Python index() string method returns the first index position where the substring was found from the input string. If no string is found then the function raises an exception.

Python index() Syntax

The syntax for the Python index() string function is as follows:

                    

string.index(substr, start, end)

Note – This method is case sensitive, for example, it will consider python and Python as 2 different words.

index() Parameters

The index() function accepts 3 parameters:

  • substr (Required) – the substring to be searched in the string
  • start (Optional) – the start position from where the substring is to be searched
  • end (Optional) – the end position till where the substring is to be searched

Note – If the start and end parameters are not specified, the default values of start = 0 and end = length-1 (end of the string) are considered.

The start index and end index parameters are useful if you want to limit your search for the substring to a specific part of the string. For example, if you have a string with 100 characters and want to search for the substring from the 30th to the 80th character, you can use the start index and end index parameters which make your job easier.

Return value from index()

The Python index() function returns the following:

  • If the substring is found inside the input string, it returns the index value position at which the first occurrence of the substring was found. It returns an integer value.
  • If the substring was not found in the input string, the function throws a ValueError exception.

Example 1: Python index() With substring Argument only

If the substring is found multiple times in the input string, the index() function only returns the index value of the first occurrence of that substring.

Note – The indexing in Python starts from 0 and not 1. To understand the basic operability of the Python index(), let us look at the subsequent program.

Example

                    

# Python program to illustrate index()
msg = 'I am going to eat food at night'
print("Index of substring 'going':", msg.index('going'))
print("Index of substring 'eat':", msg.index('eat'))
# 'at' occurs 2 times, but index of first occurrence is printed
print("Index of substring 'at':", msg.index('at'))
print('')

msg2 = 'Python Programming python programming'
# method is case sensitive
print("Index of substring 'python':", msg2.index('python'))
# notice difference between Pro and pro
print("Index of substring 'Pro':", msg2.index('Pro'))
# searches index of first occurrence of m
print("Index of substring 'm':", msg2.index('m'))
# searches index of first occurrence of i
print("Index of substring 'i':", msg2.index('i'))

Output

                    

Index of substring 'going': 5
Index of substring 'eat': 14
Index of substring 'at': 15

Index of substring 'python': 19
Index of substring 'Pro': 7
Index of substring 'm': 13
Index of substring 'i': 15

Example 2: index() With start and end Arguments

Example

                    

# Python program to illustrate index()
s = 'are you having a party at your house?'

# specifying start and end parameters
print("Index of 'a':", s.index('a', 20, 30))
print("Index of 'a':", s.index('a', 5, 10))

print("Index of 'ar':", s.index('ar', 0, 12))
print("Index of 'you':", s.index('you', 15, 30))

# substring not found
print("Index of 'dinner':", s.index('dinner', 0, 40))

Output

                    

Index of 'a': 23
Index of 'a': 9
Index of 'ar': 0
Index of 'you': 26
Traceback (most recent call last):
File "", line 12, in 
ValueError: substring not found

Difference between index() and find()

Both index() and find() are identical in that they return the index position of the first occurrence of the substring from the main string.

The main difference is that Python find() produces -1 as output if it is unable to find the substring, whereas index() throws a ValueError exception.

Example

                    

s = 'Car, Bike, Bus, Cycle'
x = s.find('Plane')
print(x)

x = s.index('Plane')
print(x)

Output

                    

-1
Traceback (most recent call last):
File "", line 5, in 
ValueError: substring not found

Frequently Asked Questions

Q1. Can you index a string in Python?

There might arise a situation where the user might want to find out the position of a specific data element in the iterable. For this issue, the Python index() method is used.

Python index() built-in function is used to return the index value of the first occurrence of a substring from the input string if the substring is found. If the substring specified is not found, then it raises an exception.

The syntax for the Python index() string function is as follows:

                    

string.index(substr, start, end)

Q2. How do you find the index of a string in Python?

To find the index of a specific substring from the input string, we make use of the Python index() and find() method. The syntax for the Python index() and find() string function is as follows:

                    

string.index(substr, start, end)

string.find(substr, start, end)

Example

                    

s = 'I love to code programs in Python language'

print(s.index('code'))
print(s.find('code'))

# Index of ‘o’ from 15 to 30
print(s.index('o', 15, 30))
# Index of ‘o’ from position 20 to 35
print(s.find('o', 20, 35))

Output

The only difference between these 2 functions is that Python find() produces -1 as output if it is unable to find the substring, whereas index() throws a ValueError exception.

Q3. What are string indices in Python?

Strings are ordered sequences of character data in Python. A numeric index or key value can be used to directly access specific items in an ordered set of data. Indexing is the term used to describe this process. Indexing allows you to easily access individual characters in a string using a number value. String indexing is based on a zero-based system: the first character in the string has index 0, the next has index 1, and so on.

Example

                    

s = 'Hello World, Cars, Jimmy, Dancing'

print('Index value from 0 to 5:', s[0:5])
print('Index value from 13 to 17:', s[13:17])
print('Index value from 26 to 33:', s[26:33])

Output

                    

Index value from 0 to 5: Hello
Index value from 13 to 17: Cars
Index value from 26 to 33: Dancing

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.