1

示例:如果有两个字符串:- 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)

有没有其他方法可以在不将其转换为列表的情况下解决此问题?我感谢您的帮助。提前致谢。

4

1 回答 1

0

您可以将每个字符串转换为setthen use symmetric_difference,然后最终str.join转换回单个字符串

>>> ''.join(set(a).symmetric_difference(b))
'daeb'
于 2021-02-11T18:55:18.943 回答