Skip to content

Python string index() Function | Get index of substring

  • by

Python string index() Function is determined if string substring occurs in a string (sentence) or in a substring of a string. This function is the same as find(), but throw an exception if str not found using index() function. In this tutorial, you will learn about the index() function and some examples of use.

Python string index() Function | Get index of substring example

When you create a string in python, every string that you create Python under the hood, what it does assigns a number to each of the items of your string so it starts from 0.

Syntax

string.index(value, start, end)

Parameter

  • value – string (substring) to search  | Required
  • start – Where to start the search otherwise Default is 0 | Optional
  • end – Where to end the search. The default is to the end of the string | Optional

Return Value

Index if found otherwise throw an exception given str is not found. like this  – ValueError: substring not found

Python string index() Function Examples

This is a simple example only using value (search substring) in a sentence and print() the result in the console.

sentence = 'Python programming tutorial.'

result = sentence.index('programming')
print("Substring index is :", result)

Output: Substring index is: 7

Another example let’s find a latter, the first occurrence of letter return the index value. Searching “p” (lowercase ) in a string

sentence = 'Python programming tutorial.'

result = sentence.index('p')
print("index is:", result)

Output : index is : 7

Note: Python is case sensitive language, that why first “P” (uppercase) latter ignored.

index() function With start and end Arguments

Now let’s looks at with all arguments in index() function.

sentence = 'Python programming tutorial.'

# Substring is searched in 'gramming tutorial.'
print(sentence.index('tutorial', 10))

# Substring is searched in 'gramming tuto'
print(sentence.index('o', 10, -4))

# Substring is searched in 'programming'
print(sentence.index('programming', 7, 18))

# Substring is searched in 'programming'
print(sentence.index('easy', 7, 18))

Output: 19
22
7
......
ValueError: substring not found

Python string index() Function | Get index of substring error output

Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of Python string index are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading