python - 如何在python中对两个字符串进行按位异或?

标签 python string bitwise-operators

我想在 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/

相关文章:

c - 优化循环内的重复模数

c++:这个插入表达式是做什么的,当作为函数参数传递时它是如何工作的?

Python BaseHTTPServer.HTTPServer - 启动和停止事件的回调

Python pyserial - windows错误(二)

java - 奇怪的java字符串数组空指针异常

java - 输入系统,用户输入对象的数组位置,后跟 # 来指示数量,但它给了我一个错误

python - 为什么处理多个异常需要一个元组,而不是一个列表?

python - Selenium 不会返回文本

python - 在行 pandas python 上使用部分字符串匹配返回 DataFrame 项

C++ 将 RGBA 打包为 unsigned int