[英]Finding the difference between two strings in python
查找出現在一個字符串中但不在另一個字符串中的字符。
我嘗試使用函數s1.difference(s2)
來獲取用戶輸入的兩個字符串之間的字符差異。 但是,當程序運行時,計算機返回set()
。 如何讓我的代碼返回不同的字符? 謝謝你。
您可以使用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'
您可以像這樣使用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.