如何在Python中按位互斥或两个字符串?

发布于 2021-01-29 18:41:25

我想在python中执行按位异或两个字符串,但是在python中不允许字符串的异或。我该怎么做 ?

关注者
0
被浏览
145
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以将字符转换为整数,然后将其转换为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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看