如果我尝试输出
print(b'\x30')
,它会显示为 0。类似地,b'\x31'
显示为 1,等等。我需要显示这个字节字符串(class ),但只有一个反斜杠。
我试过了
s = br"\x30"
print(s)
但我得到的输出是
b'\\x30'
(带有两个反斜杠)。
所有转换均以 UTF-8 编码完成。
根据您在评论中所写的内容,我认为这段代码可以满足您的要求:
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())