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

在python中查找两个字符串之间的差异,python,string,set,Python,String,Set,查找出现在一个字符串中而不是另一个字符串中的字符 我尝试使用函数s1.difference(s2)来获取用户输入的两个字符串之间的字符差异。但是,当程序运行时,计算机返回set()。如何让代码返回不同的字符? 谢谢。没有副本 您可以使用来检查差异。请注意,该解决方案不考虑字符串中重复字符的可能性: In [2]: a = set('abcdef') In [4]: b = set('ihgfed') In [5]: b.difference(a) # all elements that ar

查找出现在一个字符串中而不是另一个字符串中的字符

我尝试使用函数
s1.difference(s2)
来获取用户输入的两个字符串之间的字符差异。但是,当程序运行时,计算机返回
set()
。如何让代码返回不同的字符? 谢谢。

没有副本 您可以使用来检查差异。请注意,该解决方案不考虑字符串中重复字符的可能性:

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'}
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'
如果您希望它成为一个列表:

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

检查是否多次出现 您还可以使用来处理重复字符的可能性:

In [8]: import collections
In [9]: collections.Counter(a) - collections.Counter(b)                                   
Out[9]: Counter({'c': 1, 'a': 1, 'b': 1})
或作为字符串:

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'}
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'

您可以使用
集合
进行如下操作:

a='abcd'
b=‘bcd’
diff=集合(a中的字符对应字符)-集合(b中的字符对应字符)
打印(差异)
>>>{'a'}

这是否回答了您的问题?