Home > Software design >  How to Treat Strings as Bytes in Python 3.7.9?
How to Treat Strings as Bytes in Python 3.7.9?

Time:10-24

I have a list of values as below:

byte_values = ["\x00", "\x02", ... ]

They are meant to be byte values, and I would like to convert them to ASCII. However, because there's no b in front of them, Python treats them as strings and the decode method doesn't work. Is there a way to get Python to treat these strings as bytes and convert them to actual strings that make sense?

CodePudding user response:

Try str.encode:

>>> byte_values = ["\x00", "\x02", "..." ]
>>> [b.encode() for b in byte_values]
[b'\x00', b'\x02', b'...']

For an alternate approach, you can also use the map builtin for this:

>>> byte_values = list(map(str.encode, byte_values))
>>> byte_values
[b'\x00', b'\x02', b'...']

CodePudding user response:

You need to encode the string.

byte_values = ["\x00", "\x02", "\x04"]

for string_byte in byte_values:
    print(string_byte.encode())
  • Related