简体   繁体   English

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

[英]How to XOR two strings in Python

H, I'm trying to XOR two strings (which should become hex first) in Python. H,我正在尝试在 Python 中对两个字符串(应该先变成十六进制)进行异或。 I know one way will work:我知道一种方法会奏效:

def xor_two_str(str1, str2):
    return hex(int(str1,16) ^ int(str2,16))

But I tried sth like this:但我试过这样的:

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")

This will return TypeError: ^ shouldn't be used between str, str.这将返回 TypeError: ^ 不应在 str, str 之间使用。 I don't know why.我不知道为什么。

And also this function won't work:而且这个功能也不起作用:

bcd = change_to_be_hex("12ef")
def increment_hex(hex_n):
   return hex_n + 1
result = increment_hex(bcd)
print result

The error message is : TypeError: cannot concatenate 'str' and 'int' objects I feel this is so strange:(错误信息是:TypeError: cannot concatenate 'str' and 'int' objects 我觉得这很奇怪:(

Thank you!谢谢!

Hi, The following function is returning the result of hex() which returns a string .您好,以下函数返回hex()的结果,该结果返回一个 string

def change_to_be_hex(s):
    return hex(int(s,base=16))

You should use the ^ operator on integers.您应该对整数使用^运算符。

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")

I'm not sure though that's the result you're looking for.我不确定这是否是您正在寻找的结果。 If you want to XOR two strings, it means you want to XOR each character of one string with the character of the other string.如果要对两个字符串进行异或,则意味着要将一个字符串的每个字符与另一个字符串的字符进行异或。 You should then XOR ord() value of each char or str1 with ord() value of each char of str2.然后,您应该对每个字符或 str1 的ord()值与 str2 的每个字符的ord()值进行异或。

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")

Or in one line :或者在一行中:

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")

hex returns a string, so you're trying to xor two strings. hex返回一个字符串,因此您正在尝试对两个字符串进行异或。

def change_to_be_hex(s):
   return int(s,base=16)

Should fix this.应该解决这个问题。

when you initially return hex, like in change_to_be_hex , you explicitly convert it to int .当您最初返回 hex 时,例如在change_to_be_hex ,您将其显式转换为int you need to do that throughout your code to add something to it - so, change increment_hex to:您需要在整个代码中执行此操作以向其中添加内容 - 因此,将increment_hex更改为:

return (int(hex_n) + 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM