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

时间:2018-04-23 01:22:57

标签: python

例如" l" in"你好"应该返回3.

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

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

目前我已经写过这将打印2和3,但是可以将其打印到3吗?

2 个答案:

答案 0 :(得分:1)

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

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

它会在search

中吐出s的最后一个索引

答案 1 :(得分:0)

存储并更新索引并仅在最后打印:

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)