如何在Python中按位互斥或两个字符串?
发布于 2021-01-29 18:41:25
我想在python中执行按位异或两个字符串,但是在python中不允许字符串的异或。我该怎么做 ?
关注者
0
被浏览
145
1 个回答
-
您可以将字符转换为整数,然后将其转换为x或x:
l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]
如果由于XOR而需要一个字符串,这是一个更新的函数:
def sxor(s1,s2): # convert strings to a list of character pair tuples # go through each tuple, converting them to ASCII code (ord) # perform exclusive or on the ASCII code # then convert the result back to ASCII (chr) # merge the resulting array of characters as a string return ''.join(chr(ord(a) ^ ord(b)) for a,b in zip(s1,s2))
看到它在线运行:ideone