Python Language Searching Getting the index for strings: str.index(), str.rindex() and str.find(), str.rfind()

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

String also have an index method but also more advanced options and the additional str.find. For both of these there is a complementary reversed method.

astring = 'Hello on StackOverflow'
astring.index('o')  # 4
astring.rindex('o') # 20

astring.find('o')   # 4
astring.rfind('o')  # 20

The difference between index/rindex and find/rfind is what happens if the substring is not found in the string:

astring.index('q') # ValueError: substring not found
astring.find('q')  # -1

All of these methods allow a start and end index:

astring.index('o', 5)    # 6
astring.index('o', 6)    # 6 - start is inclusive
astring.index('o', 5, 7) # 6
astring.index('o', 5, 6) #  - end is not inclusive

ValueError: substring not found

astring.rindex('o', 20) # 20 
astring.rindex('o', 19) # 20 - still from left to right

astring.rindex('o', 4, 7) # 6


Got any Python Language Question?