【问题标题】:Differences of the ord() function between Python 2.7 and 3.9Python 2.7 和 3.9 之间 ord() 函数的区别
【发布时间】:2021-09-25 06:18:26
【问题描述】:

早安各位! 我一直在尝试将用 Python 2 编写的 this code 转换为 Python 3。这是一个使用 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 中的代码完美运行,但是在测试上面的代码时(在 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 2ord() in Python 3。此外,我搜索了其他来源,但没有发现任何提及该问题的内容:

What is Python ord Function

Porting Python 2 Code to Python 3

Cheatsheet Python 2 to 3

我在看正确的位置吗?或者在这种情况下 ord() 函数不是问题吗?非常感谢您!

【问题讨论】:

  • 加密没有按照规范工作。它应该返回一个字符串,但返回一个字节对象。这些在 py 2 中相同,但在 py 3 中不同
  • 另外,for key_id, c in enumerate(content): 是即使在 py2 中也要走的路
  • 感谢您的回答!我将 encrypt() 的返回值和第一个参数 decrypt() 更改为字节。我还在字符串中包含 enumerate() 函数。感谢您指出这一点。

标签: python xor ord binascii


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-12
    • 2021-04-08
    • 1970-01-01
    • 2013-01-26
    相关资源
    最近更新 更多