我想在给定的输入字符串str中找到某个子字符串的最后一次出现的位置(或索引)。
例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3。
我该怎么做呢?
我想在给定的输入字符串str中找到某个子字符串的最后一次出现的位置(或索引)。
例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3。
我该怎么做呢?
当前回答
使用.rfind ():
>>> s = 'hello'
>>> s.rfind('l')
3
另外,不要使用str作为变量名,否则会影响内置的str()。
其他回答
如果你不想使用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 ():
>>> s = 'hello'
>>> s.rfind('l')
3
另外,不要使用str作为变量名,否则会影响内置的str()。
对于这种情况,rfind()和rindex()字符串方法都可以使用,它们都将返回子字符串所在字符串的最高索引,如下所示。
test_string = 'hello'
target = 'l'
print(test_string.rfind(target))
print(test_string.rindex(target))
但是在使用rindex()方法时应该记住一件事,如果在搜索的字符串中没有找到目标值,rindex()方法会引发ValueError [substring not found],另一方面rfind()只会返回-1。
试试这个:
s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))
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