Search code examples
pythonstringsymmetric-difference

What is the best effective way to get symmetric difference between two strings(in python)?


Example: If there are two strings:- s1 = 'cde' s2 = 'abc'

Output: 'deab'

I converted the string into a list and compared two lists.

a = 'cde'
b = 'abc'
list1 = list(a)
list2 = list(b)

diff = []
for item in list1:
      if item not in list2:
            diff.append(item)
for item in list2:
      if item not in list1:
            diff.append(item)
diff = ' '.join(map(str, diff)).replace(' ','')

print(diff)

Is there any other way to solve this problem without converting it into the list? I appreciate your help. Thanks in advance.


Solution

  • You can convert each string to a set then use symmetric_difference, then finally str.join back into a single string

    >>> ''.join(set(a).symmetric_difference(b))
    'daeb'