Python string index() Function | Get index of substring

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 index() function and some example 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 is it assigns a number to each of the items of your string so it starts from 0.

 

Syntax

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.

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

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.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.