我想要在给定的输入字符串str
中查找某个子字符串最后一次出现的位置(或索引)。
例如,假设输入字符串是str = 'hello'
,子字符串是target = 'l'
,那么它应该输出3。
我该如何实现这个功能?
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
使用str.rindex
方法。
>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2
不是想要重启一个不活跃的帖子,但由于这个问题还没有被发布...
(这是我在找到这个问题之前所做的方式)
s = "hello"
target = "l"
last_pos = len(s) - 1 - s[::-1].index(target)
解释:当你在搜索最后一次出现时,实际上你是在翻转字符串中搜索第一次出现的。了解这一点后,我使用了s[::-1]
(它返回一个反转的字符串),然后从那里索引了target
。然后我使用了len(s) - 1 - 找到的索引
,因为我们想要在未反转的(即原始的)字符串中找到索引。
但是要注意!如果target
超过一个字符,你可能找不到它在反转字符串中的位置。为了解决这个问题,使用last_pos = len(s) - 1 - s[::-1].index(target[::-1])
,它搜索target
的反转版本。
试试这个:
s = 'hello plombier pantin'
print (s.find('p'))
6
print (s.index('p'))
6
print (s.rindex('p'))
15
print (s.rfind('p'))
对于这种情况,可以使用 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。
more_itertools
库提供了查找所有字符或所有子字符串的索引工具。
给定
import more_itertools as mit
s = "hello"
pred = lambda x: x == "l"
代码
字符
现在有一个可用的rlocate
工具:
next(mit.rlocate(s, pred))
# 3
一个补充工具是locate
:
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(str, beg=0 end=len(string))
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
5
2
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
# Last Occurrence of a Character in a String without using inbuilt functions
str = input("Enter a string : ")
char = input("Enter a character to serach in string : ")
flag = 0
count = 0
for i in range(len(str)):
if str[i] == char:
flag = i
if flag == 0:
print("Entered character ",char," is not present in string")
else:
print("Character ",char," last occurred at index : ",flag)