Python find substring index in string; In this tutorial, i am going to show you how to find substring index in string in python.
To find the index or position of the first occurrence of a substring from the given string in python; so in this tutorial, i will show you two methods which is used to find the index or position of the first occurrence of a substring from the given string in python .
How to Find String Index or Position in Python
Use the following python find() and rfind() methods to find index or position of substring from string in python:
- Python String Find()
- Python String rfind()
Python String Find()
The python find() method finds the lowest substring of the given string. If the substring found in a given string, it returns index of the substring. Otherwise, it returns -1.
The syntax of find() method is:
str.find(sub[, start[, end]] )
Parameters of find() method
The find() method takes a maximum of three parameters:
- sub – It’s the substring to be searched in the str string.
- start and end (optional) – substring is searched within
str[start:end]
Return Value from python find()
The find() method returns an integer value.
- If substring exists inside the string, it returns the index of first occurence of the substring.
- If substring doesn’t exist inside the string, it returns -1.
Example 1: Python find() method with No start and end Argument
string = 'Hello python learners, welcome to python course' result = string.find('python') print("Substring 'python':", result)
Output
Substring 'python': 6
Example 2: python find() method with start and end arguments
string = 'Hello python learners, welcome to python course' # Substring is searched print(string.find('welcome ', 6, 50))
Output
23
Python String rfind()
The python rfind() method finds the highest substring of the given string. If the substring found in a given string, it returns the index of the substring. Otherwise, it returns -1.
The syntax of rfind() is:
str.rfind(sub[, start[, end]] )
Parameters of rfind() method
The rfind() method takes maximum of three parameters:
- sub – It’s the substring to be searched in the str string.
- start and end (optional) – substring is searched within
str[start:end]
Return Value from rfind() method
The rfind() method returns an integer value.
- If substring exists inside the string, it returns the highest index where substring is found.
- If substring doesn’t exist inside the string, it returns -1.
Example 1: Python rfind() method with No start and end Argument
string = 'Hello python learners, welcome to python course' result = string.rfind('python') print("Substring 'python':", result)
Output
Substring 'python': 34
Example 2: python find() method with start and end arguments
string = 'Hello python learners, welcome to python course' # Substring is searched print(string.find('to', 6, 50))
Output
31