[英]Count number of matches between two strings python
Given two strings of equal length, how do I return the number of times that the strings have the same character at a given index? 给定两个长度相等的字符串,如何返回字符串在给定索引处具有相同字符的次数?
So: count_matches("bob","boa")
would give 2
as index 0
holds the same character and so does index 1
. 所以: count_matches("bob","boa")
将给出2
因为索引0
保持相同的字符,索引1
也是如此。
But, count_matches('bob', 'bbo')
would only return 1
as the only index where the character is the same in both is index 0
. 但是, count_matches('bob', 'bbo')
只返回1
作为唯一的索引,其中两个字符在索引0
是相同的。 Although there are two 'b'
s in both, only one of those is at a corresponding index. 虽然两者中都有两个'b'
,但只有一个是相应的索引。
I assume you mean the number of indices where the character is the same in both strings. 我假设你的意思是两个字符串中字符相同的索引数。
Therefore, I would do: 因此,我会这样做:
>>> sum(a==b for a, b in zip('bob', 'boa'))
2
Wrapping that in a function should be trivial. 将其包含在函数中应该是微不足道的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.