Python String | RFIND ()



Syntax :

 str.rfind (sub, start, end) 

Parameters :

sub: It`s the substring which needs to be searched in the given string.
start: Starting position where sub is needs to be checked within the string.
end: Ending position where suffix is ​​needs to be checked within the string.

NOTE. If no start and end indices are supplied, then it defaults to 0 and length-1 as start and end indices, where end indices are not included in our search.

Return: returns the highest substring index, if found in the given string; if not found, -1 is returned.

Exception:
ValueError: This error occurs when the argument string is not found in the target string.

CODE # 1

# Python program to demonstrate how rfind () works
# in the whole line

word = `geeks for geeks`

  
# Returns the most high substring index

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 the highest substring index

result = word.rfind ( `ate ` )

print ( "Substring` ate` fo und at index: " , result)

Output:

 Substring `geeks` found at index: 10 Substring` for` found at index: 6 Substring `ate` found at index: 13 

CODE # 2

# Python program to demonstrate how rfind () works
# in a substring

word = ` geeks for geeks`

 
# The substring is searched for in & # 39; eeks for geeks & # 39;

print (word.rfind ( `ge` , 2 ))

 < br /> # The substring is searched for in & # 39; eeks for geeks & # 39;

print (word.rfind ( `geeks` , 2 ))

  
# The substring is searched for in & # 39; eeks for geeks & # 39;

print ( word.rfind ( `geeks` , 2 ))

 
# The substring is searched for in & # 39; s for g & # 39;

print (word.rfind ( `for` , 4 , 11 ))

Output:

 10 10 -1 6 

Practical Application:
Useful when validating strings. Check if the given substring is present in any string or not.

# Python program to demonstrate how rfind () works
# search string

word = `CatBatSatMatGate`

  

if (word.rfind ( `Ate` )! = - 1 ):

print ( "Contains given substring" )

else :

print ( "Doesn`t contains given substring" )

Output:

 Doesn`t contains given substring