在两个字符串中共同出现的字符 [英] Occurence of characters in common in two strings

查看:132
本文介绍了在两个字符串中共同出现的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to use a for loop to calculate the number of times a character in one string occurs in another string.

例如如果string1 ='python'和string2 ='boa constrictor',则应计算为6(2 t,3 o,1 n)

e.g. if string1 = 'python' and string2 = 'boa constrictor' then it should calculate to 6 (2 t's, 3 o's, 1 n)

有人知道怎么做吗?

推荐答案

非常简单:

count = 0

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

print(count)

这篇关于在两个字符串中共同出现的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆