Python 2 vs 3原始字节输出

2024-10-04 05:28:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

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相关的东西编写的

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

但是在Python3中,它会打印 245148103178837822864207104random1random2

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

提前谢谢


Tags: 代码importlenosticketurandompython3list
1条回答
网友
1楼 · 发布于 2024-10-04 05:28:57

在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方法将bytes.decode转换为字符串:

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

相关问题 更多 >