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/rindex和find/之间的区别rfind是,如果在字符串中找不到子字符串,将会发生什么:
astring.index('q') # ValueError:找不到子字符串 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) # -结束不包含在内
ValueError:找不到子字符串
astring.rindex('o', 20) # 20 astring.rindex('o', 19) # 20 - still from left to right astring.rindex('o', 4, 7) # 6