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

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

我该怎么做呢?


当前回答

使用str.rindex方法。

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

其他回答

more_itertools库提供了查找所有字符或所有子字符串索引的工具。

鉴于

import more_itertools as mit


s = "hello"
pred = lambda x: x == "l"

Code

字符

现在有rlocate工具可用:

next(mit.rlocate(s, pred))
# 3

一个补充的工具是定位:

list(mit.locate(s, pred))[-1]
# 3

mit.last(mit.locate(s, pred))
# 3

子字符串

还有一个window_size参数可用来定位几个项的前导项:

s = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?"
substring = "chuck"
pred = lambda *args: args == tuple(substring)

next(mit.rlocate(s, pred=pred, window_size=len(substring)))
# 59

使用str.rindex方法。

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2
str = "Hello, World"
target='l'
print(str.rfind(target) +1)

or

str = "Hello, World"
flag =0
target='l'
for i,j in enumerate(str[::-1]):
    if target == j:
       flag = 1
       break;
if flag == 1:   
    print(len(str)-i)

如果你不想使用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

不试图复活一个不活跃的帖子,但由于这还没有发布…

(这是我在发现这个问题之前是怎么做的)

s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)

解释:在搜索最后一个出现项时,实际上是在搜索反转字符串中的第一个出现项。知道了这一点,我做了s[::-1](它返回一个反向的字符串),然后从那里索引目标。然后我做了len(s) - 1 -找到的索引,因为我们想要在未反转的(即原始的)字符串中找到索引。

不过要小心!如果target不止一个字符,则可能在反向字符串中找不到它。为了解决这个问题,使用last_pos = len(s) -1 - s[::-1].index(target[::-1]),它会搜索target的反向版本。