首页 > 解决方案 > Python 2 vs 3 原始字节输出

问题描述

我有以下代码

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 的方式输出代码?

提前致谢。

标签: pythonpython-3.xpython-2.7types

解决方案


在 Python 2bytes中是字符串字符序列,因此通过调用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 3bytes中是一个 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使用以下方法将其转换为字符串bytes.decode

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

推荐阅读