Getting the index for strings str.index str.rindex and str.find str.rfind

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents