简体   繁体   中英

Python printing bytes strangely

So, I have this very simple code:

from construct import VarInt

a = VarInt.build(12345)
print(a)
with open('hello.txt', 'wb') as file:
    file.write(a)

When I print "a", it shows only the first byte and the last byte for some reason does not show properly. It prints "b'\xb9`'" and it should print "b'\xb9\x60'", or at least that's what I would like to print. Now, when I look at the file that I stored, it saves the bytes exactly how it should with no issue there. Does anybody know what's going on here? Also, with some integers it prints properly, but with this one, for example, does not.

It's not a single byte but

b'\xb9`'

Do You see "`" after 9 ? It's a character encoded as 0x60 . If You want to display all bytes as hexadecimal You can try this snippet:

print(" ".join(hex(n) for n in a))

Why do you think that is does not print properly? Assuming an ASCII derived code page(ASCII, UTF-8 or latin), the code for the back quote (`) is 96 or 0x60.

As \xb9 does not map to a character in your system code page, it is escaped, but as \x60 does map to the back quote, the representation just uses that character.

try doing file.close() . This saves the file and prevent weird things from happening

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM