我想在给定的输入字符串str中找到某个子字符串的最后一次出现的位置(或索引)。

例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3。

我该怎么做呢?


当前回答

如果你不想使用rfind,那么这个可以使用/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

其他回答

您可以使用rfind()或rindex() 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

区别在于当子字符串未找到时,rfind()返回-1,而rindex()引发异常ValueError (Python2链接:ValueError)。

如果您不想检查rfind()返回代码-1,您可能更喜欢rindex(),它将提供一个可以理解的错误消息。否则,你可能会在你的代码中搜索意外值-1的分钟…


示例:搜索最后一个换行符

>>> txt = '''first line
... second line
... third line'''

>>> txt.rfind('\n')
22

>>> txt.rindex('\n')
22

您可以使用rindex()函数来获取字符串中字符的最后一次出现

s="hellloooloo"
b='l'
print(s.rindex(b))

试试这个:

s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))

使用str.rindex方法。

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

如果你不想使用rfind,那么这个可以使用/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos