两个字符串中共同字符的出现

时间:2012-03-16 05:43:39

标签: python for-loop

我想使用 for 循环来计算一个字符串中的字符出现在另一个字符串中的次数。

e.g。如果string1 ='python'和string2 ='boa constrictor'那么它应该计算为6(2 t,3 o,1 n)

有谁知道怎么做?

2 个答案:

答案 0 :(得分:2)

非常简单:

count = 0

for letter in set(string1):
  count += string2.count(letter)

print(count)

答案 1 :(得分:0)

使用dict comprehension {ch:string2.count(ch) for ch in string1 if ch in string2}

我忘了你需要一个for循环并对所有字母求和。

count = 0 
for ch in string1:
    if ch in string2:
        count += string2.count(ch)