Computer >> Computer tutorials >  >> Programming >> Python

How to search a string in backwards direction in Python?


Python has a rfind() method which searches from the end of a string for the occurrence of a substring. It returns the index of the last occurrence if found, else -1. You can use it as follows:

>>> "CocacolaPepsi".rfind('cola')
4
>>> 'CocacolaPepsi'.rfind('coke')
-1