我想在给定的输入字符串str中找到某个子字符串的最后一次出现的位置(或索引)。
例如,假设输入字符串是str = 'hello',子字符串是target = 'l',那么它应该输出3。
我该怎么做呢?
我想在给定的输入字符串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
其他回答
Python String rindex()方法
描述 Python字符串方法rindex()返回子字符串str所在的最后一个索引,如果不存在这样的索引则引发异常,可选地将搜索限制为字符串[beg:end]。
语法 下面是rindex()方法−的语法
str.rindex(str, beg=0 end=len(string))
参数 str:指定要搜索的字符串。
beg−起始索引,默认为0
len -这是结束索引,默认等于字符串的长度。
返回值 此方法返回最后一个索引,否则将在未找到str时引发异常。
例子 下面的例子展示了rindex()方法的用法。
现场演示
! / usr / bin / python
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
当我们运行上述程序时,它会产生以下结果−
5
2
参考:Python String rindex()方法 ——Tutorialspoint
# 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)
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)
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
如果你不想使用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