Python 查找字符串中最后一个字母的索引

Python 查找字符串中最后一个字母的索引,python,Python,例如,“hello”中的“l”应该返回3 search = input() s = input() start=0 for idx, letter in enumerate(s): if letter == search: print (idx) 目前,我已经编写了这篇文章,它将打印2和3,但是有可能只打印3吗?您可以使用rfind()方法。像这样: search = input() #if user input is l s = input() #and user

例如,“hello”中的“l”应该返回3

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

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

目前,我已经编写了这篇文章,它将打印2和3,但是有可能只打印3吗?

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

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

它在
s

中弹出
搜索的最后一个索引,存储并更新索引,仅在末尾打印:

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)

你为什么用“无”作为字符串?@BOi“太多”工作只是一种意见。这是试图坚持和补充OP的原始代码。使用内置函数当然是一个好主意,但也不会教你太多东西……这不是一个很好的类比,学习按位运算有很好的理由。这两个答案在技术上都是正确的。那么为什么不让OP来决定呢。客观地说,
rfind
是更快、更具自动化的解决方案,但这不是一个错误的答案。@BOi这是一个愚蠢的论点。您是否从未重新实施过快速排序或其他不仅仅是为了学习?我很想听听原因。这似乎是一个完美的解决方案。@PaulRooney正是我的想法。你不时会有人进来,在所有答案上都贴上DV。对此无能为力。