简体   繁体   English

在python中找到两个字符串之间的差异

[英]Finding the difference between two strings in python

Find the characters that occur in one string but not the other.查找出现在一个字符串中但不在另一个字符串中的字符。

I have tried using the function s1.difference(s2) to get the difference in characters between two strings that are inputted from the user.我尝试使用函数s1.difference(s2)来获取用户输入的两个字符串之间的字符差异。 However, when the program is run the computer returns set() .但是,当程序运行时,计算机返回set() How can I get my code to return the different character(s)?如何让我的代码返回不同的字符? Thank you.谢谢你。

Without duplicates没有重复

You can use set to check the difference.您可以使用set来检查差异。 Be aware that this solution does not consider the possibility of duplicate characters within a string:请注意,此解决方案不考虑字符串中出现重复字符的可能性:

In [2]: a = set('abcdef')
In [4]: b = set('ihgfed') 
In [5]: b.difference(a)  # all elements that are in `b` but not in `a`.
Out[5]: {'g', 'h', 'i'}

In [6]: b ^ a   # symmetric difference of `a` and `b` as a new set
Out[6]: {'a', 'b', 'c', 'g', 'h', 'i'}

If you want it to be a list:如果你希望它是一个列表:

In [7]: list(b.difference(a))                                                             
Out[7]: ['i', 'g', 'h']

Check for multiple occurrences检查是否多次出现

You can also use Counter to treat the possibility of duplicate characters:您还可以使用Counter来处理重复字符的可能性:

In [8]: import collections
In [9]: collections.Counter(a) - collections.Counter(b)                                   
Out[9]: Counter({'c': 1, 'a': 1, 'b': 1})

Or as a string:或者作为字符串:

In [15]: c = collections.Counter('abcccc') - collections.Counter('cbd')                   

In [16]: c                                                                                
Out[16]: Counter({'a': 1, 'c': 3})

In [17]: ''.join(c.elements())
Out[17]: 'accc'

You can use sets for that like this:您可以像这样使用sets

a = 'abcd'
b = 'bcd'

diff = set(char for char in a) - set(char for char in b)
print(diff)

>>> {'a'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM