[英]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'示例:如果有两个字符串:- s1 = 'cde' s2 = 'abc'
Output: 'deab' 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.
提前致谢。
You can convert each string to a set
then use symmetric_difference
, then finally str.join
back into a single string您可以将每个字符串转换为一个
set
,然后使用symmetric_difference
,最后str.join
回单个字符串
>>> ''.join(set(a).symmetric_difference(b))
'daeb'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.