获得两个字符串(在 python 中)之间的对称差异的最有效方法是什么?

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

示例: 如果有两个字符串:- s1 = 'cde' s2 = 'abc'

输出:'deab'

我将字符串转换成一个列表并比较了两个列表。

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)

有没有其他方法可以解决这个问题而不把它转换成列表? 我感谢您的帮助。提前致谢。

您可以将每个字符串转换为 set,然后使用 symmetric_difference,最后 str.join 转换回单个字符串

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