Python finds the last occurrence in string | Example code

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)

Output:

Python finds the last occurrence in string

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.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.