Change language

Python | Find the last occurrence of a substring

| |

Method # 1: Using rindex()

This method returns the last occurrence of a substring if present in a string. The disadvantage of this function is that it throws an exception if there is no substring in the string, and therefore breaks the code.

# Python3 demo code
# Find the last occurrence of a substring
# using rindex ()

 
# initialization string

test_string = "GfG is best for CS and also best for Learning"

 
# target word initialization

tar_word = "best"

 
# prints the original strings

print ( "The original string : " + str (test_string))

 
# using rindex ()
# Find the last occurrence of a substring

res = test_string.rindex (tar_word)

 
# print result

print ( "Index of last occurrence of substring is: " + str (res))

Output:

 The original string: GfG is best for CS a nd also best for Learning Index of last occurrence of substring is: 28 

Method # 2: Using rfind()

This is an alternative method to accomplish this task. The advantage that this function offers better than the above method is that this function returns "-1" if the substring is not found, instead of throwing an error.

# Python3 demo code
# Find the last occurrence of a substring
# using rfind ()

 
# initialization string

test_string = "GfG is best for CS and also best for Learning"

 
# target word initialization

tar_word = "best"

  
# print the original line

print ( "The original string:" + str (test_string))

 
# using rfind ()
# Find the last occurrence of a substring

res = test_string.rfind (tar_word)

 
# print result

print ( "Index of last occurrence of substring is:" + str (res))

Output:

 The original string: GfG is best for CS and also best for Learning Index of last occurrence of substring is: 28 

Python | Find the last occurrence of a substring find: Questions

Python | Find the last occurrence of a substring Python functions: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method