Python Bytes to String to Bytes [duplicate]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我知道以前曾经问过类似的事情,但还没有答案。

我创建了一个字节字符串:salt = os.urandom(16),它提供了类似于:b'w\x05\xce^f\xdcbM\xe9\xb8c\x8b\x98\xd2\n\x11'的内容

我需要的是将它提供给用户,以便他们可以复制和粘贴,将其放在文本文档或任何地方,然后将其粘贴回终端。

简而言之。我需要将其转换为字符串。然后回到它的编码。

我尝试了salt.decode(encoding="utf-8")和许多变化,它们都给了我一些形式的UnicodeDecodeError: 'utf-8' codec can't...,唯一似乎工作的是"".join(map(chr, salt)),但我无法弄清楚如何扭转这一点。

提前致谢。附:我在Python 3中工作

python string python-3.x character-encoding python-unicode
1个回答
1
投票

python模块binsascii很可能是你需要的。例:

>>> import os
>>> salt = os.urandom(16)
>>> import binascii
>>> binascii.b2a_hex(salt)
'9df7cc8d135fb9f115e166e140153217'
>>> binascii.a2b_hex(binascii.b2a_hex(salt))
'\x9d\xf7\xcc\x8d\x13_\xb9\xf1\x15\xe1f\xe1@\x152\x17'

还有许多其他编码。

© www.soinside.com 2019 - 2024. All rights reserved.