Python 2.7 和 3.9 之间 ord() 函数的差异

Differences of the ord() function between Python 2.7 and 3.9

大家早上好! 我一直在尝试将 Python 2 中编写的 this code 转换为 Python 3.It 的一个使用 XOR 加密字符串的简单函数。我目前拥有的:

import binascii

def encrypt(content: str, key: str) -> str:
    key_id = 0
    xored = ""
    for c in content:
        xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
        key_id += 1
    return binascii.hexlify(xored.encode())

def decrypt(content: str, key: str) -> str:
    key_id = 0
    xored = ""
    for c in binascii.unhexlify(content):
        xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
        key_id += 1
    return binascii.hexlify(xored.encode())

Python 2 中的代码完美运行,但是在测试上面的代码 (in Python 3) 时,我在解码消息时遇到问题. (encrypt() 函数似乎运行良好。) 出现以下错误:

>>> encrypt("foo", "123")
b'575d5c'
>>> decrypt(b"575d5c", "123")
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    decrypt(b"575d5c", "123")
  File "/home/user/Code/Python/xorcrypt.py", line 15, in decrypt
    xored += chr(ord(key[key_id % len(key)]) ^ ord(c))
TypeError: ord() expected string of length 1, but int found

我检查了两个文档,但无法识别版本之间的任何差异:ord() in Python 2 and ord() in Python 3。此外,我搜索了其他来源,但没有找到任何提及该问题的信息:

What is Python ord Function

Porting Python 2 Code to Python 3

Cheatsheet Python 2 to 3

我看对地方了吗?或者在这种情况下 ord() 函数不是问题所在?非常感谢您!

区别不在于ord(),而在于binascii.unhexlify()。在 Python 2 中,它是 returns 一个字符串,如果你对该字符串进行索引,你会得到一个长度为 1 的字符串,你可以在其上调用 ord()。但是在 Python 3 它 returns a bytes 如果你索引它,你会得到一个你不能调用 ord() 的小整数,也不需要到.