Python Reverse Find in String

user156027 picture user156027 · Aug 21, 2010 · Viewed 81.8k times · Source

I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index.

An example: I want to find the index of the 2nd I by using the index and str.rfind()

s = "Hello, I am 12! I like plankton but I don't like Baseball."
index = 34 #points to the 't' in 'but'
index_of_2nd_I = s.rfind('I', index)
#returns = 36 and not 16 

Now I would expect rfind() to return the index of the 2nd I (16) but it returns 36. after looking it up in the docs I found out rfind does not stand for reverse find.

I'm totally new to Python so is there a built in solution to reverse find? Like reversing the string with some python [::-1] magic and using find, etc? Or will I have to reverse iterate char by char through the string?

Answer

Blair Conrad picture Blair Conrad · Aug 21, 2010

Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:

>>> s = "Hello, I am 12! I like plankton but I don't like Baseball."
>>> index = 34 #points to the 't' in 'but'
>>> index_of_2nd_I = s.rfind('I', 0, index)
>>>
>>> index_of_2nd_I
16