我想在 python 中执行两个字符串的按位异或,但在 python 中不允许对字符串进行异或。我该怎么做?
最佳答案
您可以将字符转换为整数并进行异或运算:
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
关于python - 如何在python中对两个字符串进行按位异或?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2612720/