简体   繁体   中英

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. However, when the program is run the computer returns 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. 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:

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:

a = 'abcd'
b = 'bcd'

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

>>> {'a'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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