查找字符串中最后出现的字母的索引

2024-04-20 09:15:09 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,“hello”中的“l”应该返回3。你知道吗

search = input()
s = input()
start=0

for idx, letter in enumerate(s):
    if letter == search:
        print (idx)

目前我已经写了这将打印2和3,但有可能得到这只是打印3?你知道吗


Tags: inhelloforinputsearchifstartprint
2条回答

您可以使用rfind()方法。像这样:

search = input() #if user input is l
s = input() #and user input is hello
print (s.rfind(search)) #returns 3

它在s中吐出search的最后一个索引

存储和更新索引并仅在末尾打印:

s = "hello"
search = 'l'

last_found = None
for idx, letter in enumerate(s):
    if letter == search:
        last_found = idx
print (last_found)

或按相反顺序循环:

for idx in range(len(s)-1,-1,-1):
    if s[idx] == search:
        break
print (idx)

相关问题 更多 >