查找出现在一个字符串中但不在另一个字符串中的字符。
我尝试使用函数VALUES (?, ?, now(), now() + interval 1 hour, curdate())
来获取用户输入的两个字符串之间的字符差异。但是,运行该程序时,计算机将返回s1.difference(s2)
。如何获得我的代码以返回不同的字符?
谢谢。
答案 0 :(得分:1)
您可以使用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 [7]: list(b.difference(a))
Out[7]: ['i', 'g', 'h']
您还可以使用Counter
来处理重复字符的可能性:
In [8]: import collections
In [9]: collections.Counter(a) - collections.Counter(b)
Out[9]: Counter({'c': 1, 'a': 1, 'b': 1})
或作为字符串:
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'
答案 1 :(得分:-1)
您可以像这样使用sets
:
a = 'abcd'
b = 'bcd'
diff = set(char for char in a) - set(char for char in b)
print(diff)
>>> {'a'}