计算Python中一对字符串中匹配字符的数量
我们得到两个字符串。我们需要找到第一个字符串中也存在于第二个字符串中的字符的计数。
带套
set函数为我们提供字符串中所有元素的唯一值。我们还使用&运算符来查找两个给定字符串之间的公共元素。
示例
strA = 'nhooo.com'
uniq_strA = set(strA)
# Given String
print("Given String\n",strA)
strB = 'aeio'
uniq_strB = set(strB)
# Given String
print("Search character strings\n",strB)
common_chars = uniq_strA & uniq_strB
print("Count of matching characters are : ",len(common_chars))输出结果
运行上面的代码给我们以下结果-
Given String nhooo.com Search character strings aeio Count of matching characters are : 3
与研究
我们使用re模块中的搜索功能。我们使用一个count变量,并在搜索结果为true时保持递增。
示例
import re
strA = 'nhooo.com'
# Given String
print("Given String\n",strA)
strB = 'aeio'
# Given String
print("Search character strings\n",strB)
cnt = 0
for i in strA:
   if re.search(i, strB):
      cnt = cnt + 1
print("Count of matching characters are : ",cnt)输出结果
运行上面的代码给我们以下结果-
Given String nhooo.com Search character strings aeio Count of matching characters are : 5