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'