Use the Python rfind() method to finds 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)
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)
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)
Note: Don’t use
str as a variable name or you’ll shadow the built-in
Do comment if you have any suggestions or doubts on this Python string topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.