Python String rfind() Method
The rfind() function returns the index number of the last occurrence of a substring (plain text) in the specified string (case sensitive). If the substring is not found, it returns -1. The difference between it and the find() function is that it starts the search process from the last index in the text to be searched for to the first index in it.
How to formulate it like this:
string. rfind(sub, start, end)
Parameters:
substring : (required) A substring that must be searched for in the given string.
start ( optional ) : ( Optional ) The starting position where the sub-string within the string needs to be checked.
End ( ) : ( Optional ) The index of the end within the string that the search ends with. The default is the end of the string
Return value: The rfind() function returns an integer of the index number of the last occurrence of a substring (plain text) in the given string. If the substring is not found, it returns -1.
We will use the rfind() function without the optional ( start ) and ( ( end ) parameters. We'll just use the substring parameter to find the index number of the last occurrence of a substring inundefined specified string.
In the following example, we will search for the index number of the last occurrence of the substring represented by the word (python),
Example:
# The string to be searched
string = "learn python With ahmed obaid"
# Searches the given string for the index number of the last occurrence of the substring and returns an integer
print(string. rfind("python"))
The output will be:
6
In the following example, we will use the rfind() function with optional (start) and (end) parameters.
Example:
# The string to be searched
string = "learn python With ahmed obaid"
# Searches the given string for the index number of the last occurrence of the substring and returns an integer
# Noting that we started the search from index #2
print(string. rfind ("aid", 2))
# Searches the given string for the index number of the last occurrence of the substring and returns an integer
# Noting that we started the search process from index number 0 to the end index number 10
print(string. rfind ("learn", 0, 10))
# Searches the given string for the index number of the last occurrence of the substring and returns an integer
# Indicating that we have started undefined The search process from index No. 2 to the end index No. 30
print(string. rfind ("obaid", 10, 30))
The output will be:
26
0
24
External sources:
Built-in functions - official Python documentation
If you have any questions or concerns, leave them in the comments
Tags
Python python data types Python String string methods python String search functions in Python python string rfind method
Share page
About author
Ahmed Obaid
Hello, I am Ahmed Obaid, an Egyptian Arabic programmer. I would like to put my experiences learning Python on this site So that it will be a reference for you and me as well.
Sign up to leave a comment