当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

比较两个字符串并检查它们共有多少个字符

  1. from collections import Counter
  2. def shared_chars(s1, s2):
  3. return sum((Counter(s1) & Counter(s2)).values())
  4. print(shared_chars('car', 'carts'))

Output:

  1. 3