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

后端 未结 12 1802
攒了一身酷
攒了一身酷 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条回答
  •  难免孤独
    2020-12-01 03:12

    Based on William McBrine's answer, here is a solution for fixed-length strings which is 9% faster for my use case:

    import itertools
    import struct
    def make_strxor(size):
        def strxor(a, b, izip=itertools.izip, pack=struct.pack, unpack=struct.unpack, fmt='%dB' % size):
            return pack(fmt, *(a ^ b for a, b in izip(unpack(fmt, a), unpack(fmt, b))))
        return strxor
    strxor_3 = make_strxor(3)
    print repr(strxor_3('foo', 'bar'))
    

提交回复
热议问题