Updated June 22, 2023
Introduction to Python Find String
The string is a sequence of characters. The character can be any letter, digit, whitespace character, or special symbol. Strings in Python are immutable, meaning they cannot be modified once created. However, we can copy the string and perform various operations. Python provides a separate class, “str,” for string handling and manipulations. One such operation is to find the index of a substring from the given string. Python provides three built-in methods to perform the find operation. find() method is similar to the index() method, which also returns the index of a matched substring, but the difference is that find() and rfind() returns -1 if the item to be searched is not found, whereas index() throws an error.
Syntax of Python Find String
The syntax of Python find string is as follows:
1. find()
The find() method identifies the location of the first occurrence of the searched substring.
Syntax:
string_object.find(substring, start, end)
Parameters:
- substring: The text or substring needs to be searched in the string “string_object.” This is a mandatory parameter.
- start: An optional parameter that specifies the position where searching has to start. The default value is 0. It means searching will start from the beginning of the string.
- end: An optional parameter that specifies the position where searching has to stop. The default value is (length-1).
2. rfind()
This is similar to the find() method. The search performs from the right to the left of the string.
Syntax:
string_object.rfind(substring, start, end)
Parameters:
- substring: Text to search.
- start: start specifies the index from where searching has to start. The default value is 0, and length-1 for the start parameter.
- end: end specifies the index from where searching stops, respectively. The default value is 0, and length-1 for the stop parameter.
3. index()
index() also returns the index of the searched item’s first occurrence but throws an error if the item to search is not found in the string.
Syntax:
string_object.index(substring, start, end)
Parameters:
- substring: Text to search.
- start: start specifies the index from where searching has to start. The default value is 0, and length-1 for the start parameter.
- end: end specifies the index from where searching stops, respectively. The default value is 0, and length-1 for the stop parameter.
Examples of Python Find String
Below we will see the examples of Python find string:
Example #1
Python code to show the functionality of the find() method.
Code:
"""
find() is used to find the index of substring/text in the given string
"""
print('Illustration of find() with no start and end parameters')
string = "what comes easy won't last \nwhat lasts won't come easy"
print("Input String :")
print(string)
print("index of newline :", string.find('\n'))
print("index of (won't) :", string.find("won't"))
print("index of (come) :", string.find('come'))
print("index of (easier) :", string.find('easier'))
print('\n')
print('Illustration of find() with start and end parameters')
print("index of (won't) :", string.find("won't", 18)) # start : 18
print("index of (come) :", string.find('come', 5, 15)) # start : 5 and stop = 15
print("index of (come) :", string.find('come', 10)) # start : 10
Output:
Explanation:
find() with no start and stop parameters:
- Index of newline’ \n’ is printed.
- Index of the first occurrence Python Finds String will not be printed as multiples will not be printed in the specified string. Similarly, the index of come is printed.
- As ‘easier’ is not present in the string, so -1 will be returned.
find() with start and stop parameters:
- The start index of the second occurrence of “won’t” is 18.
- The start index of the first occurrence of “come” is 5, and the stop index is 15.
- The second occurrence of come is printed as start index = 10.
Example #2
Python code to illustrate the functionality of the rfind() method.
Code:
"""
rfind() is used to find the index of substring/text from right to left in the given string
"""
print('Illustration of rfind() with no start and end parameters')
string = "XYZX\n987\nYZX\n05LMN"
print("input string :")
print(string)
print('\n')
print("index of newline :", string.rfind('\n'))
print("index of (ZX) :", string.rfind("ZX"))
print("index of (X) :", string.rfind('X'))
print("index of (ABC) :", string.rfind('ABC'))
print('\n')
print('Illustration of rfind() with start and end parameters')
print("index of (ZX) :", string.find('ZX', 0, 9)) # start : 0 and stop : 9
print("index of (X) :", string.find('X', 0, 10)) # start : 0 and stop : 10
print("index of newline :", string.find('\n', 6, 10)) # start : 6 and stop : 10
Output:
Explanation:
- rfind() with no start and end parameters.
- The program prints the index or position of the first occurrence of ‘\n’ from the right side of the string.
- The program prints the indexes of the first occurrence of ZX and X from the right side.
- As substring, ABC is not present, so -1 will be returned.
- rfind() with start and stop parameters.
- Provide start and stop indexes in the rfind() method call to print the second occurrences of ZX and X from the right side.
- Similarly, the second occurrence of newline’ \n’ is printed as a start: 6 and stop: 10, as shown in the output.
Example #3
Python code to show the functionality of the index() method.
Code:
"""
index() is used to find the index of substring/text in the given string
"""
print('<--------illustration of index()-------->')
string = "Python is an interpreted language"
print("input string :")
print(string)
print('\n')
print("index of (an) :", string.index('an'))
print("index of (space) :", string.index(" "))
print("index of (space) :", string.index(' ', 20)) # start : 20
print('\n')
print('Alert ! this will throw an error!!')
try:
print("index of (compiled) :", string.index('compiled'))
except:
print("index() will throw an error in case a substring is not found")
Output:
x
Explanation:
- Index() works similarly to find(), but the major difference is their handling of the non-matched substring.
- If a substring is not present in the given string, then find() will return -1, whereas index() will throw an error.
- The try-except block manages the error in the example provided.
Conclusion
Python provides various built-in methods to find a particular text’s index or substring in a given string. find(), find(), and index(), by default, returns the index of the first occurrence of the text. However, we can find all the matched substrings’ possible occurrences or indexes using loops and some programming logic.
Recommended Articles
We hope that this EDUCBA information on “Python Find String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.