Use the Python rfind() method to find the last occurrence in the string. This function returns a “-1” if a substring (char) is not found.
string.rfind(value, start, end)
Note: If the value is not found, the rfind() method returns -1, but the rindex() method will raise an exception:
Find the index of the last occurrence of a substring in a string
Simple examples code.
Find the last occurrence of the string “and” example
txt = "Python and example and code"
res = txt.rfind("and")
print(res)
Output:
Search char between position 5 and 10 and its last occurrence
txt = "Python and example and code"
res = txt.rfind("a", 5, 10)
print(res)
Output: 7
How to Find the last occurrence of a character in String Python
Find the last occurrence of char “o” in a given string.
txt = "Python and example and code"
res = txt.rfind("o")
print(res)
Output: 24
Note: Don’t use str
as a variable name or you’ll shadow the built-in str()
.
Do comment if you have any suggestions or doubts on this Python string topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.