【问题标题】:Why does ord() fail when porting from Python 2 to Python 3?为什么从 Python 2 移植到 Python 3 时 ord() 会失败?
【发布时间】:2017-11-13 09:29:17
【问题描述】:

我正在尝试将名为 heroprotocol 的 Python 库从 Python 2 移植到 Python 3。该库用于解析来自名为《风暴英雄》的在线游戏的回放文件,目的是从文件中获取数据 (即谁与谁交手,他们什么时候死去,比赛什么时候结束,谁赢了等等)。

这个库似乎是为 Python 2 创建的,由于我使用的是 Python 3(特别是 Anaconda、Jupyter notebook),我想将其转换为 Python 3。

我遇到的具体问题是当我跑步时

header = protocol.decode_replay_header(mpq.header['user_data_header']['content'])

应该得到一些关于回放文件的基本数据,我得到这个错误:

TypeError: ord() expected string of length 1, but int found

我用谷歌搜索了ord() 函数,发现了一些关于在 Python 3 中使用 ord() 的帖子,但没有一个能解决我遇到的问题。我也在 Github 的“问题”部分尝试了posting,但我还没有得到任何回复。

为什么我会看到这个错误?

【问题讨论】:

    标签: python python-3.x typeerror python-2.x ord


    【解决方案1】:

    根据你提出的issue,异常发生在line 69 of decoders.py

    self._next = ord(self._data[self._used])
    

    这在 Python 2 中成功但在 Python 3 中失败的明显原因是 self._data 是一个字节串。在 Python 2 中,字节串是“标准”字符串对象,因此索引到一个会返回该位置的字符(本身就是一个字符串)……

    # Python 2.7
    >>> b'whatever'[3]
    't'
    

    ... 并在结果上调用 ord() 的行为与预期一致:

    >>> ord(b'whatever'[3])
    116
    

    但是,在 Python 3 中,everything is different:标准字符串对象是 Unicode 字符串,而字节字符串是整数序列。因此,对字节串的索引直接返回相关的整数……

    # Python 3.6
    >>> b'whatever'[3]
    116
    

    ...所以在该整数上调用 ord() 毫无意义:

    >>> ord(b'whatever'[3])
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: ord() expected string of length 1, but int found
    

    因此,您应该能够通过简单地删除对ord() 的调用以及类似的行来防止您在此处询问的特定异常:

    self._next = self._data[self._used]
    

    ……当然,结果可能会发现更多问题(超出此问题的范围)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-18
      • 2017-01-31
      • 1970-01-01
      • 2019-09-06
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多