Python 程序计算字符串对中匹配字符的数量

2024 年 8 月 29 日 | 4 分钟阅读

在本教程中,我们将讨论用户如何编写一个 Python 程序来计算给定字符串对中匹配字符的数量。

我们将传入一对非空字符串。该程序将计算这对字符串中匹配字符的数量。在这里,我们将考虑传入的字符串中包含重复字符。

示例

方法 1

  • 步骤 1:我们将计数器变量初始化为 0。
  • 步骤 2:我们将遍历第一个字符串,从第一个字符到最后一个字符。
  • 步骤 3:如果从 string_1 提取的字符在 string_2 中找到。并且如果该字符在 string_1 中的第一次出现索引与当前提取的字符的索引相同,那么它将计数器值加 1。

然后我们将使用 Python 中的 string.find('character') 来查找相同的字符。如果找到,它将返回字符在字符串中的第一次出现索引;否则,它将返回“-1”。

示例

  • 步骤 4:打印计数器的输出值。

示例:方法 1

输出

Please enter the characters for String 1:  ajg 78y
Please enter the characters for String 2:  gjy 23r
The no. matching characters in the pairs of strings:  2

方法 2

  • 步骤 1:在此方法中,我们将使用 set() 函数删除给定字符串中的重复项。
  • 步骤 2:我们将对两个字符串使用 set(intersection)。
  • 步骤 3:我们将使用 len() 函数计算 "matched_characters_1" 字符串的长度。

示例 2:方法 2

输出

Please enter the characters for String 1:  awe ret #$65
Please enter the characters for String 2:  rty urw @!34 
The number matching characters in the pairs of strings: 4

方法 3

  • 步骤 1:我们将导入 Re 模块。
  • 步骤 2:我们将使用 re.search() 函数来检查 string_1 的任何字符是否存在于 string_2 中,如果存在,则将 1 添加到计数器变量中。

示例 3:方法 3

输出

Please enter the characters for String 1: learning
Please enter the characters for String 2: working
The number matching characters in the pairs of strings: 5

结论

在本教程中,我们讨论了编写 Python 程序来计算给定字符串对中匹配字符数量的不同方法。