- Python String rfind() Method
- Syntax
- Parameters
- Return Value
- Example
- Example
- Example
- Example
- Python rfind: Find Index of Last Substring in String
- Python rfind: Find the Index of Last Substring in String
- How to Use Python rfind In a Substring
- Differences Between Python rfind and rindex
- Check if a substring only exists one time in a Python String
- Conclusion
- Python String rfind() Method
- Definition and Usage
- Syntax
- Parameter Values
- More Examples
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Python String rfind() Method
The Python String rfind() method searches for the starting index of a last occurrence of a specified substring is found in an original string. Unlike the rindex() method, which raises an exception if the substring is not present, this method returns -1.
This method performs the search in two scenarios:
- It searches the entire string from the 0th index to the end index, or,
- It searches a part of the string, from the ith index to jth index, where i < j.
Syntax
Following is the syntax for Python String rfind() method −
Parameters
- str − This specifies the string to be searched.
- start − This is the starting index, by default its 0.
- end − This is the ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found and -1 otherwise.
Example
When we pass a substring of the original string as a parameter to the method, the return value will be the index of the substring in the string.
The following example shows the usage of Python String rfind() method. Here, we create a string, say «This is a string», and pass a substring of this string, say «is», as an argument to the method. The method finds the index of this substring in the input string.
str1 = "This is a string"; str2 = "is"; print("The index of substring:") print(str1.rfind(str2))
When we run above program, it produces following result −
Example
When we pass a substring that is not a part of the original string as a parameter to the method, the return value will be -1.
In this example, we will create a string: «This is a string» as input and pass another string «Hello» as an argument to the method. Since the string does not contain the argument, the method returns -1.
str1 = "This is a string"; print("The index of substring:") print(str1.rfind('Hello"'))
Let us run the program above, the output is obtained as follows −
Example
We pass optional parameters to the method determining the range of the search, the method will return the occurrence of the string within that range.
In the given program, we take a string as an input. We pass three parameters to the method called on this input string: a substring, a beginning index and an ending index. The method searches for the specified substring within the limit and returns the index.
str1 = "This is a string"; print("The index of substring:") print(str1.rfind('is', 2, 5))
The output for the program above is given as follows −
Example
We pass optional parameters to the method determining the range of the search and the substring is not present in the given range, the method will return -1.
In the given program, we pass three parameters to the method called on an input string created: a substring, a beginning index and an ending index. The method searches for the specified substring within the limit and returns the index. The return value will be -1 if the substring is not present in the limit specified.
str1 = "This is a string"; print("The index of substring:") print(str1.rfind('st', 0, 10))
Let us run the program to display the output as follows −
Python rfind: Find Index of Last Substring in String
In this tutorial, you’ll learn how to use the Python rfind() method, which uses Python to find the last index substring in a string. Essentially, this method searches from the right and returns the index of the right-most substring.
You’ll learn how to use the Python .rfind() method, how to use its parameters, how it’s different from .rindex() , and how to use the method to see if a substring only exists once in a string.
The Quick Answer: Return the Index of the Right-Most Occurrence of a Substring
Python rfind: Find the Index of Last Substring in String
The Python .rfind() method works similar to the Python .find() method.
The .find() method searches for a substring in a string and returns its index. However, the .rfind() method searches from the right side of the text and returns the first index it finds – meaning, it returns the last index of a given substring in a string.
Some important things to note about the .rfind() method:
- The index returned marks the starting index of a substring (i.e., a multi-letter substring would return the index of the first letter)
- If we substring doesn’t exist, then the method returns -1
Let’s see how we can use the .rfind() method to find the index of the last substring of a string in Python:
# Use Python .rfind() to Find Index of Last Substring sentence = 'She sells seashells by the sea-shore' idx = sentence.rfind('sea') print(idx) # Returns 27
We can see here that the method returned the index position of 27 .
Now let’s search for a substring that we know doesn’t exist:
# Use Python .rfind() to Find Index of Last Substring sentence = 'She sells seashells by the sea-shore' idx = sentence.rfind('buys') print(idx) # Returns -1
We can see here that searching for ‘buys’ returns an index position of -1 , indicating that the substring doesn’t exist in the string.
In the next section, you’ll learn how to use the Python .rfind() and its parameters to search within a substring of a larger string.
How to Use Python rfind In a Substring
The Python .rfind() method also lets you search within a substring of a larger string, by using its start= and end= parameters.
Let’s see how we can limit the substring search:
# Use Python .rfind() to Find Index of Last Substring Using start= and end= sentence = 'She sells seashells by the sea-shore' print(sentence.rfind('sea', 5, 20)) # Searches: 'ells seashells ' print(sentence.rfind('sea', 0, 30)) # Searches: 'She sells seashells by the sea' print(sentence.rfind('sea', 0, -1)) # Searches: 'She sells seashells by the sea-shor' # Returns: # 10 # 27 # 27
We can see here that the Python .rfind() method can be used to only search in substrings of a larger string.
In the next section, you’ll learn the differences between two very similar methods, the rfind and rindex methods.
Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.
Differences Between Python rfind and rindex
Python has two very similar methods: .rfind() and .rindex() .
The two methods do exactly the same thing, with one notable difference: the .rfind() method will not fail is a given substring doesn’t exist, while the .rindex() method will raise a ValueError .
Let’s see how this works in practice:
# Difference between .rfind() and .rindex() sentence = 'She sells seashells by the sea-shore' print(sentence.rfind('buys')) print(sentence.rindex('buys')) # Returns: # -1 # ValueError: substring not found
We can see here that when searching for a substring that doesn’t exist, the .rfind() method will allow your program to continue.
In the next section, you’ll learn how to use the rfind method to see if a substring only exists once in a Python string.
Want to learn more about Python f-strings? Check out my in-depth tutorial, which includes a step-by-step video to master Python f-strings!
Check if a substring only exists one time in a Python String
There may be times when you want to see if a substring only exists once in a Python string.
In order to do this, you can use the Python .rfind() method in conjunction with the Python .find() method.
The way that this will work is to compare whether the two methods return the same index. The reason behind this is that if the index of the first and the last instance of a substring is the same, then the substring only exists a single time.
# Check if a substring only exists once in a string sentence = 'She sells seashells by the sea-shore' def single_substring(string, substring): return string.rfind(substring) == string.find(substring) print(single_substring(sentence, 'seashells')) print(single_substring(sentence, 'sea')) # Returns: # True # False
Let’s explore what we’ve done here:
- We defined a function single_substring() , which takes a string and a substring as its arguments
- The function returns a boolean value by evaluating whether the output of the .rfind() and the .find() methods are the same
- The function will return True if the string only exists once and False if it exists multiple times (or not at all)
In this section, you learned how to use the Python rfind method to see if a string only exists a single time in a larger string.
Want to learn how to use the Python zip() function to iterate over two lists? This tutorial teaches you exactly what the zip() function does and shows you some creative ways to use the function.
Conclusion
In this tutorial, you learned how to use the Python .rfind() method. The method searches a Python string for a substring and returns the index of the rightmost substring. If no substring is found, then the value of -1 is returned.
You learned how to use the method and all of its arguments. You also learned how to use the method’s arguments to search only in a substring. You also learned the differences between the Python .rfind() and .rindex() methods. Finally, you learned how to implement the .rfind() method from scratch.
To learn more about the .rfind() method, check out the official documentation here.
Python String rfind() Method
Where in the text is the last occurrence of the string «casa»?:
Definition and Usage
The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method. See example below.
Syntax
Parameter Values
Parameter | Description |
---|---|
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
More Examples
Example
Where in the text is the last occurrence of the letter «e»?:
txt = «Hello, welcome to my world.»
Example
Where in the text is the last occurrence of the letter «e» when you only search between position 5 and 10?:
txt = «Hello, welcome to my world.»
Example
If the value is not found, the rfind() method returns -1, but the rindex() method will raise an exception:
txt = «Hello, welcome to my world.»
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.