Introduction to Python Find String
The string is a sequence of characters. The character can be any letter, digit, whitespace character, or any special symbols. Strings in Python are immutable, which means once created, they cannot be modified. However, we can make a copy of the string and can perform various operations on it. For this, 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 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
Syntax of python find string are as follows:
1. find()
find() method returns the index of the first occurrence of the substring to be searched.
Syntax:
string_object.find(substring, start, end)
Parameters:
- substring: It’s the text or substring that needs to be searched in 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. Default value is (length-1).
2. rfind()
This is similar to find() method. The difference is, the search is performed from 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 a start and stop parameters:
- The second occurrence won’t is printed as start index = 18.
- The first occurrence of come is printed as start index = 5 and stop index = 15.
- The second occurrence of come is printed as start index = 10.
Example #2
Python code to illustrate the functionality of 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.
- index or position of the first occurrence of ‘\n’ from the right side of the string is printed.
- similarly, indexes of the first occurrences of ZX and X from the right side are printed.
- As substring, ABC is not present, so -1 will be returned.
- rfind() with a start and stop parameters.
- second occurrences of ZX and X from the right side are printed as start and stop indexes are provided in rfind() method call.
- 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:
Explanation:
- Index() works in the same way as to find(), but the major difference is their way of handling for non matched substring.
- If a substring is not present in the given string, then find() will return -1, whereas index() will throw an error.
- In the above example, the error is handled using a try-except block.
Conclusion
Python provides various built-in methods to find a particular text’s index or substring in a given string. find(), rfind() and index() by default returns the index of the first occurrence of the text. However, using loops and some programming logic, we can find all the matched substrings’ possible occurrences or indexes.
Recommended Articles
This is a guide to Python Find String. Here we discuss the syntax and parameters of Python Find String along with Examples and its code implementation. You may also have a look at the following articles to learn more –