可以使用Python内置的set()函数,将两个字符串转换成集合,再使用交集操作符“&”来找到两个集合中都存在的部分。
示例代码如下:
string1 = "hello world"
string2 = "hello everyone"
set1 = set(string1)
set2 = set(string2)
common = set1 & set2
common_str = ''.join(common)
print(common_str) # 输出结果为:'hel o'
此方法会将两个字符串中所有重复的字符都找出来,如果需要找的是单词或字符串,可以使用split()方法来首先将字符串按照空格或其他符号划分为列表,再使用上述方法来找到公共部分。
上一篇:比较字符串,然后对比进行评分。
下一篇:比较字符数组中的数字元素