A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-string-rfind-method/ below:

Python String rfind() Method - GeeksforGeeks

Python String rfind() Method

Last Updated : 21 Feb, 2025

Python String rfind() method returns the rightmost index of the substring if found in the given string. If not found then it returns -1.

Example Python
s = "GeeksForGeeks"
print(s.rfind("Geeks"))

Explanation

Syntax of rfind() method

str.rfind(sub, start, end)

Parameters

Return Type

Note: If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and ending indexes where ending indexes are not included in our search.

Examples of rfind() Method 1. Basic usages of Python String find() Method Python
word = 'geeks for geeks'

# Returns highest index of the substring
res = word.rfind('geeks')
print (res )

res = word.rfind('for')
print (res )

word = 'CatBatSatMatGate'

# Returns highest index of the substring
res = word.rfind('ate')
print(res)

Explanation

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.

Python
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))

Explanation

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.

Python
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

Explanation



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4