Python String rfind() Method Example
Python3
string = "w3wiki" print (string.rfind( "Geeks" )) |
Output:
8
Example 1: Basic usages of Python String find() Method
Python3
word = 'geeks for geeks' # Returns highest index of the substring result = word.rfind( 'geeks' ) print ( "Substring 'geeks' found at index :" , result ) result = word.rfind( 'for' ) print ( "Substring 'for' found at index :" , result ) word = 'CatBatSatMatGate' # Returns highest index of the substring result = word.rfind( 'ate' ) print ( "Substring 'ate' found at index :" , result) |
Output:
Substring 'geeks' found at index : 10 Substring 'for' found at index : 6 Substring 'ate' found at index : 13
Example 2: Using Python String rfind() Method with given start and end position inside String
If we pass the start and end parameters to the Python String rfind() Method, it will search for the substring in the portion of the String from its right side.
Python3
# Python program to demonstrate working of rfind() # in a sub-string word = 'geeks for geeks' # Substring is searched in 'eeks for geeks' print (word.rfind( 'ge' , 2 )) # Substring is searched in 'eeks for geeks' print (word.rfind( 'geeks' , 2 )) # Substring is searched in 'eeks for geeks' print (word.rfind( 'geeks ' , 2 )) # Substring is searched in 's for g' print (word.rfind( 'for ' , 4 , 11 )) # finding substring using -ve indexing print (word.rfind( 'geeks' , - 5 )) |
Output:
10 10 -1 6 10
Example 3: Practical Application
Here, we check one email address and the Top Level Domain (TLD) matching our necessary condition. Then we print, “Email matched” else “Email not matched”, followed by the TLD String. Even if this email address contains a “.com” substring, rfind() helped to extract the TLD string more efficiently.
Python3
email = 'userxyz.com@domain.xyz' last_dot_pos = email.rfind( '.' , 1 ) tld_string = email[last_dot_pos:] if tld_string = = ".com" : print ( "Email matched" ) else : print ( "Email not matched, tld:" , tld_string) |
Output:
Email not matched, tld: .xyz
Python String rfind() Method
Python String rfind() method returns the rightmost index of the substring if found in the given string. If not found then it returns -1.