Python find substring in string; In this tutorial, you will learn how to find substring in string using string function find() and rfind() in python. As well as learn how to find the first occurrence from a Python string and how to find the last string occurrence from a Python string.
Python if you have a string. And you want to search/find any substring in that string. So this python find string example is only for you.
Substrings are found in Python strings in two ways. Such as finding ways are python find last arriving in string, and python find first origin in string.
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