【问题标题】:Python 2 vs 3 raw bytes outputPython 2 vs 3 原始字节输出
【发布时间】:2021-01-23 00:34:53
【问题描述】:

我有以下代码

import os
unk2 = os.urandom(10)
totlen = len("lol1") + len("lol2")
ownershipsectionwithsig = "random1" + "random2"
ticket = list(unk2) + list(ownershipsectionwithsig)
ticket = "".join(map(str, ticket))


print(ticket)

代码用于我正在测试的与 RNG 相关的东西。

在 python 2 中,它打印以下 ?zoռv3L??random1random2

但是在 python 3 中它会打印 245148103178837822864207104random1random2

由于某种原因,python 3 不像 python 2 那样显示原始字节输出,而是将其转换为某种东西。我将如何更改我的代码,以便 python 3 以 python 2 的方式输出代码?

提前致谢。

【问题讨论】:

    标签: python python-3.x python-2.7 types


    【解决方案1】:

    在 Python 2 中,bytes 是字符串字符序列,因此通过调用 list(unk2) 将其转换为列表会将其转换为单字符串列表:

    Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:19:30) [MSC v.1500 32 bit (Intel)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> unk2 = os.urandom(10)
    >>> list(unk2)
    ['[', '\x12', '\xfa', '\x98', '\x87', '\x1e', '\n', '\xd1', '\xe2', '\x17']
    

    在 Python 3 中,bytes 是一个 8 位整数序列,因此通过调用 list(unk2) 将其转换为列表,将其转换为整数列表,并将每个整数映射为字符串并将它们连接在一起最后得到一长串数字:

    Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> unk2 = os.urandom(10)
    >>> list(unk2)
    [65, 77, 240, 11, 233, 106, 204, 69, 171, 214]
    

    如果您想让 Python 3 像在 Python 2 中一样将随机字节序列输出为字符串,您可以使用 bytes.decode 方法将 bytes 转换为字符串:

    unk2 = os.urandom(10).decode('latin-1')
    

    【讨论】:

    • 我不知道该怎么办
    • 好的,谢谢,但是我不喜欢只使用答案而不知道为什么会起作用,那么为什么解码器需要 latin-1 而不是 utf-8?
    • latin-1 是标准的 8 位字符编码,适合输出字节的字符串表示。 utf-8 是 1 到 3 个字节的编码,取决于第一个字节的第 8 位,而其余字节也必须遵循特定的范围,所以很可能来自 os.urandom 的随机生成的字节将无法解码为utf-8
    • @EmilB:原始随机字节几乎从来都不是有效的 UTF-8(UTF-8 是自检的)。 Latin-1 是一种编码(至少在 Python 上)将字节值 0 到 255 映射到等效的 Unicode 序数 0 到 255。所以它总是成功的,它是从原始字节到字符串的最自然映射,你可能得到。也就是说,其中一些字节是不可打印的(ASCII 本身包含大量不可打印的字符,而 latin-1 是 ASCII 的超集),所以这不是一个好主意。如果要打印原始字节,通常可以将它们打印为十六进制或 base64 编码。
    猜你喜欢
    • 2011-07-27
    • 2018-11-03
    • 2015-11-02
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 2015-01-17
    • 2021-05-07
    相关资源
    最近更新 更多