how to do bitwise exclusive or of two strings in python?

后端 未结 12 1799
攒了一身酷
攒了一身酷 2020-12-01 02:34

I would like to perform a bitwise exclusive or of two strings in python, but xor of strings are not allowed in python. How can I do it ?

12条回答
  •  旧时难觅i
    2020-12-01 03:06

    You can convert the characters to integers and xor those instead:

    l = [ord(a) ^ ord(b) for a,b in zip(s1,s2)]
    

    Here's an updated function in case you need a string as a result of the 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))
    

    See it working online: ideone

提交回复
热议问题