例如" l" in"你好"应该返回3.
search = input()
s = input()
start=0
for idx, letter in enumerate(s):
if letter == search:
print (idx)
目前我已经写过这将打印2和3,但是可以将其打印到3吗?
答案 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)