查找string中最后一个子string的索引
我想查找给定的inputstringstr某个子string的最后一次出现的位置(或索引)。
例如,假设input的string是str = 'hello' ,子string是target = 'l' ,那么它应该输出3。
我怎样才能做到这一点?
使用.rfind() :
>>> s = 'hello' >>> s.rfind('l') 3
也不要使用str作为variables名称,否则会影响内置的str() 。
你可以使用rfind()或rindex()
Python2链接: rfind() rindex()
s = 'Hello StackOverflow Hi everybody' print( s.rfind('H') ) 20 print( s.rindex('H') ) 20 print( s.rfind('other') ) -1 print( s.rindex('other') ) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: substring not found
不同的是,当找不到子string时, rfind()返回-1而rindex()引发exceptionValueError (Python2链接: ValueError )。
如果你不想检查rfind()返回码-1 ,你可能更喜欢rindex() ,它会提供一个可以理解的错误信息。 否则,您可以search分钟,其中意外的值-1来自您的代码…
使用str.rindex方法。
>>> 'hello'.rindex('l') 3 >>> 'hello'.index('l') 2
尝试这个:
s = 'hello plombier pantin' print (s.find('p')) 6 print (s.index('p')) 6 print (s.rindex('p')) 15 print (s.rfind('p'))