String rfind() Method in Python

Python String rfind() Method

In Python, the rfind() method is a built-in string method that allows you to search a string for a particular substring, starting from the end of the string. It returns the highest index of the substring if found, and -1 if the substring is not present. The search is case-sensitive, meaning it differentiates between lowercase and uppercase characters.

The syntax of the rfind() method is as follows:

str.rfind(substring, start, end)

Here, str is the string on which you want to perform the search. The substring is the sequence of characters you want to find in the string. The optional parameters start and end define the slice of the string within which the search will be performed. The search for the substring will only be done within the indices start and end-1.

Here are some examples to illustrate how the rfind() method works:

sentence = "This is a sample sentence. This sentence is a sample."

# Basic usage
index1 = sentence.rfind("sentence")
print(index1)  # Output: 41

# Specifying start and end parameters
index2 = sentence.rfind("sentence", 0, 20)
print(index2)  # Output: -1 (Substring not found within the specified slice)

# Case-sensitive search
index3 = sentence.rfind("Sentence")
print(index3)  # Output: -1 (Substring not found due to case-sensitive search)

# Finding the last occurrence of a substring
index4 = sentence.rfind("sentence", 0, 50)
print(index4)  # Output: 41 (Index of the last occurrence within the specified slice)

In the first example, the rfind() method finds the last occurrence of the word "sentence" and returns the index 41, which is the starting index of that occurrence.

The second example shows that if the substring is not found within the specified slice (0 to 20), the method returns -1.

The third example demonstrates that the rfind() method performs a case-sensitive search. Since "Sentence" is not the same as "sentence", the method returns -1.

In the fourth example, the method returns 41 because it still finds the last occurrence of "sentence" within the specified slice (0 to 50), which starts at index 41.