2

I would like to open a file in Python 3.9 in binary format, but it looks like the ASCII signs are not getting interpreted as bytes.

My code:

f = open("Unbenannt.png",'rb').read()[0:10]

print(f)

I get this output:

b'\x89PNG\r\n\x1a\n\x00\x00'

How do I get it like this?

b'\x89\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00'
0

1 Answer 1

4

you are confusing representation with the thing being represented... you have bytes

by default a bytestring representation converts printable ascii characters to their printable ascii character

if you want to interpret it as integers from 0-255

file_bytes = b'1234567\x119A'
print([b for b in file_bytes])
# [49, 50, 51, 52, 53, 54, 55, 17, 57, 65]

if you want to have a list of hex strings

print([f'{b:02x}' for b in file_bytes])
# ['31', '32', '33', '34', '35', '36', '37', '11', '39', '41']

if you want just a single string with \xXX instead of any ascii you can do almost the same

print(''.join([f'\\x{b:02x}' for b in file_bytes]))
# '\x31\x32\x33\x34\x35\x36\x37\x11\x39\x41'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.