python - 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 的方式输出代码?
提前致谢。
解决方案
在 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')
推荐阅读
- crystal-reports - *更新*水晶报表:选择专家公式不提取所有数据
- angular - Wordpress 和 Angular 7. 如何获取资产路径?
- selenium - 无法使用 Javascriptexecutor 在输入文本框中输入文本
- python - 当networkx中节点度数为n时合并边
- python-3.x - 如何从 API 获取结果,而不仅仅是响应代码
- sql - 将财政年度和财政季度转换为年月
- java - 如何在java中处理黄瓜步骤中的逻辑或运算
- javascript - Javascript函数仅适用于我的模态内的第一行
- arrays - 猫鼬一个接一个地填充
- google-cloud-spanner - Spanner - 按复合主键行为搜索