在 Python 中查找两个字符串之间的公共字符

在 Python 中查找两个字符串之间的共同字符

Find common characters between two Strings in Python

查找两个字符串之间的共同字符:

  1. 使用set()该类将第一个字符串转换为set.
  2. 使用intersection()方法获取常用字符。
  3. 使用该str.join()方法将 连接set成一个字符串。
主程序
string1 = 'abcd' string2 = 'abzx' common_characters = ''.join( set(string1).intersection(string2) ) print(common_characters) # 👉️ 'ab'

set()类接受一个可迭代的可选参数,并返回一个新对象set,其中的元素取自可迭代对象。

主程序
string1 = 'abcd' # 👇️ {'d', 'c', 'b', 'a'} print(set(string1))
Set 对象存储唯一元素的无序集合并实现intersection()方法。

交集
方法返回一个新

,其中包含两个
对象
set共有的元素。set

主程序
string1 = 'abcd' string2 = 'abzx' # 👇️ {'a', 'b'} print(set(string1).intersection(string2))

最后一步是使用该str.join()方法将set对象连接成一个字符串。

主程序
string1 = 'abcd' string2 = 'abzx' common_characters = ''.join( set(string1).intersection(string2) ) print(common_characters) # 👉️ 'ab' print(len(common_characters)) # 👉️ 2

str.join方法将一个可迭代对象作为参数并返回一个字符串,该字符串是可迭代对象中字符串的串联。

调用该方法的字符串用作元素之间的分隔符。

len()如果需要获取两个字符串之间共同元素的数量,可以使用该函数。

或者,您可以使用列表理解。

使用列表理解查找两个字符串之间的公共字符

查找两个字符串之间的共同字符:

  1. 使用列表理解来迭代第一个字符串。
  2. 检查第二个字符串中是否存在每个字符。
  3. 使用该str.join()方法将列表连接成一个字符串。
主程序
string1 = 'abcd' string2 = 'abzx' common_characters = ''.join([ char for char in string1 if char in string2 ]) print(common_characters) # 👉️ 'ab' print(len(common_characters)) # 👉️ 2

我们使用列表理解来迭代第一个字符串。

列表推导用于对每个元素执行某些操作或选择满足条件的元素子集。

在每次迭代中,我们检查当前字符是否存在于另一个字符串中并返回结果。

in 运算符
测试成员资格

例如,如果是 的成员,则
x in s计算为 ,否则计算为TruexsFalse

如果您需要获取两个字符串之间的公共字符列表,请删除对该str.join()方法的调用。

主程序
string1 = 'abcd' string2 = 'abzx' common_characters = [ char for char in string1 if char in string2 ] print(common_characters) # 👉️ ['a', 'b'] print(len(common_characters)) # 👉️ 2

或者,您可以使用简单的for循环。

Find common characters between two Strings using a for loop #

To find the common characters between two strings:

  1. Use a for loop to iterate over the first string.
  2. Check if each character is present in the second string.
  3. Use the str.join() method to join the list into a string.
main.py
string1 = 'abcd' string2 = 'abzx' common_characters = [] for char in string1: if char in string2: common_characters.append(char) print(common_characters) # 👉️ ['a', 'b'] print(''.join(common_characters)) # 👉️ 'ab'

We used a for loop to iterate over the first string.

On each iteration, we use the in operator to check if the character is
contained in the second string.

If the condition is met, we append the character to a list.

The
list.append()
method adds an item to the end of the list.

main.py
my_list = ['bobby', 'hadz'] my_list.append('com') print(my_list) # 👉️ ['bobby', 'hadz', 'com']

The method returns None as it mutates the original list.

您选择哪种方法是个人喜好的问题。我会使用列表理解,因为我发现它们非常直接且易于阅读。