为什么b'\x30'显示为0?

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

如果我尝试输出

print(b'\x30')
,它会显示为 0。类似地,
b'\x31'
显示为 1,等等。我需要显示这个字节字符串(class ),但只有一个反斜杠。

我试过了

s = br"\x30"
print(s)

但我得到的输出是

b'\\x30'
(带有两个反斜杠)。 所有转换均以 UTF-8 编码完成。

python python-3.x encoding byte
1个回答
0
投票

根据您在评论中所写的内容,我认为这段代码可以满足您的要求:

s = "00200001001         0"
print("".join(f"\\x{ord(c):02x}" for c in s)

请注意,这仅在

ord(c)
< 256. If you have characters outside of the ASCII table, I recommend this instead (even if all non-ASCII characters have
ord(c)
< 256):

时有效
s = "00200001001         0"
print("".join(f"\\x{b:02x}" for b in s.encode())
© www.soinside.com 2019 - 2024. All rights reserved.