In Python, the string rfind() function is very useful. We can use the rfind() Python function to find the last occurrence in a string of a character or substring.

string_variable = "This is a string variable we will search."

pos_of_last_a = string_variable.rfind("a")
pos_of_last_w = string_variable.rfind("w")

print(pos_of_last_a)
print(pos_of_last_w)

#Output:
36
29

When working with string variables in Python, being able to search and get the position of substrings and characters in string variables is very useful.

One such capability is to find the first or last occurrence of a substring in a string.

There are many great string methods in Python, and we can find the last occurrence of a character or substring using the Python string rfind() function.

The rfind() Python function, or reverse find function, returns the position of the last occurrence of a given substring in a string.

If rfind() doesn’t find the given substring, then it returns -1.

Below is an example in Python to find the position of the last time a string appears in another string using rfind().

string_variable = "This is a string variable we will search to try to find some other strings."

pos_of_last_a = string_variable.rfind("a")
pos_of_last_to = string_variable.rfind("to")
pos_of_last_string = string_variable.rfind("string")

print(pos_of_last_a)
print(pos_of_last_to)
print(pos_of_last_string)
print(pos_of_last_z)

#Output:
36
48
67
-1

If you want to do the opposite and find the first occurrence in a string using Python, you can use the find() function.

Using the Start and End Arguments of the Python rfind() Function

The Python rfind() function allows us to pass optional “start” and “end” arguments to only search a specific substring of the string for the occurrence of a character or substring.

For example, if we only wanted to search the first 10 characters, we would pass “0” and “10” to rfind().

string_variable = "This is a string variable we will search to try to find some other strings."

pos_of_last_a = string_variable.rfind("a")
pos_of_last_a_first_10 = string_variable.rfind("a",0,10)

print(pos_of_last_a)
print(pos_of_last_a_first_10)

#Output:
36 
8

Hopefully this article has been useful for you to learn how to use the Python rfind() function to find the last occurrence in string of a character or substring using Python.

Categorized in:

Python,

Last Update: March 15, 2024