[英]comparing strings in python
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 =“ aaaaa”和target =“ aa”,输出应为3,而不是4。我试图获取两个字符串进行比较的最后位置
Currently what you're doing is comparing each character from the search
string in reverse order and seeing if it's in target
. 当前,您正在做的是按照相反的顺序比较
search
字符串中的每个字符,并查看它们是否在target
。 If it is, you prematurely return the wrong index. 如果是这样,则过早返回了错误的索引。
Instead, I would recommend using the str.rfind
method: 相反,我建议使用
str.rfind
方法:
>>> 'aaaaa'.rfind('aa')
3
str.rfind
is basically the same thing as the str.index
method except it searches for the first needle from the right of the haystack. str.rfind
与str.index
方法基本相同,只是它从干草堆的右边搜索第一根针。
Edit: In order to treat empty needles as being present at the rightmost index, you can use the following return expression: 编辑:为了将空针视为出现在最右边的索引处,可以使用以下返回表达式:
def find_last(search, target):
return target and search.rfind(target) or len(search)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.