def find_last(search, target):
for index, character in reversed(list(enumerate(search))):
if character in target:
return index
else:
return -1
suppose search="aaaaa" and target="aa", output should=3, not 4. I am trying to get the last position where the two strings compare
最佳答案
当前您正在做的是以相反顺序比较 search
字符串中的每个字符,并查看它是否在 target
中。如果是,您就会过早地返回错误的索引。
相反,我建议使用 str.rfind
方法:
>>> 'aaaaa'.rfind('aa')
3
str.rfind
基本上与 str.index
方法相同,只不过它从大海捞针的右侧搜索第一根针。
编辑:为了将空针视为存在于最右侧索引处,您可以使用以下返回表达式:
def find_last(search, target):
return target and search.rfind(target) or len(search)
关于python - 在Python中比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29484029/