如何在 Python 中异或两个字符串

Lal*_*oon 6 python python-2.7

H,我正在尝试在 Python 中对两个字符串(应该先变成十六进制)进行异或。我知道一种方法会奏效:

def xor_two_str(str1, str2):
    return hex(int(str1,16) ^ int(str2,16))
Run Code Online (Sandbox Code Playgroud)

但我试过这样的:

def change_to_be_hex(str):
    return hex(int(str,base=16))
def xor_two_str(str1,str2):
    a = change_to_be_hex(str1)
    b = change_to_be_hex(str2)
    return hex(a ^ b)
print xor_two_str("12ef","abcd")
Run Code Online (Sandbox Code Playgroud)

这将返回 TypeError: ^ 不应在 str, str 之间使用。我不知道为什么。

而且这个功能也不起作用:

bcd = change_to_be_hex("12ef")
def increment_hex(hex_n):
   return hex_n + 1
result = increment_hex(bcd)
print result
Run Code Online (Sandbox Code Playgroud)

错误信息是:TypeError: cannot concatenate 'str' and 'int' objects 我觉得这很奇怪:(

谢谢!

pix*_*xis 10

嗨,以下函数返回结果hex()返回一个字符串

def change_to_be_hex(s):
    return hex(int(s,base=16))
Run Code Online (Sandbox Code Playgroud)

您应该^在整数上使用运算符。

def change_to_be_hex(s):
    return int(s,base=16)
    
def xor_two_str(str1,str2):
    a = change_to_be_hex(str1)
    b = change_to_be_hex(str2)
    return hex(a ^ b)
print xor_two_str("12ef","abcd")
Run Code Online (Sandbox Code Playgroud)

我不确定这是否是您正在寻找的结果。如果要对两个字符串进行异或,则意味着要将一个字符串的每个字符与另一个字符串的字符进行异或。然后,您应该ord()对每个字符或 str1 的ord()值与 str2 的每个字符的值进行异或。

def xor_two_str(a,b):
    xored = []
    for i in range(max(len(a), len(b))):
        xored_value = ord(a[i%len(a)]) ^ ord(b[i%len(b)])
        xored.append(hex(xored_value)[2:])
    return ''.join(xored)
    
print xor_two_str("12ef","abcd")
Run Code Online (Sandbox Code Playgroud)

或者在一行中:

def xor_two_str(a,b):
    return ''.join([hex(ord(a[i%len(a)]) ^ ord(b[i%(len(b))]))[2:] for i in range(max(len(a), len(b)))])

print xor_two_str("12ef","abcd")
Run Code Online (Sandbox Code Playgroud)