Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert bytes to a string

I'm using this code to get standard output from an external program:

>>> from subprocess import * >>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] 

The communicate() method returns an array of bytes:

>>> command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n' 

However, I'd like to work with the output as a normal Python string. So that I could print it like this:

>>> print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2 

I thought that's what the binascii.b2a_qp() method is for, but when I tried it, I got the same byte array again:

>>> binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar  3 07:03 file2\n' 

How do I convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be OK with Python 3.

like image 816
Tomas Sedovic Avatar asked Mar 03 '09 12:03

Tomas Sedovic


People also ask

How do you convert bytes to string in Java?

Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .

Is byte [] same as string?

Byte objects are sequence of Bytes, whereas Strings are sequence of characters. Byte objects are in machine readable form internally, Strings are only in human readable form. Since Byte objects are machine readable, they can be directly stored on the disk.

Can we convert byte to char?

To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


1 Answers

You need to decode the bytes object to produce a string:

>>> b"abcde" b'abcde'  # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. >>> b"abcde".decode("utf-8")  'abcde' 

See: https://docs.python.org/3/library/stdtypes.html#bytes.decode

like image 143
Aaron Maenpaa Avatar answered Sep 20 '22 08:09

Aaron Maenpaa