獲取字串的索引 str.index() str.rindex() 和 str.find() str.rfind()

String 也有 index 方法,但也有更高階的選項和額外的 str.find。對於這兩者,存在互補的反向方法。

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

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

index / rindexfind / rfind 之間的區別是如果在字串中找不到子字串會發生什麼:

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

所有這些方法都允許開始和結束索引:

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:找不到子字串

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

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