Dwarika Nath
Dwarika Nath

Reputation: 19

How to convert <class bytes> to array or string in python?

subprocess.popen is returning the output as class bytes as below

b'Caption FreeSpace Size \r\r\nC: 807194624
63869808640 \r\r\nD: \r\r\nY:
216847310848 2748779065344 \r\r\n\r\r\n'

How to remove all occurance of \r\r\n Or how can I convert this to python string or array

Upvotes: 0

Views: 7021

Answers (3)

Unnamed
Unnamed

Reputation: 21

You can print it by:

print(b'Caption FreeSpace ... \r\r\n\r\r\n'.decode())    

Result:

Caption FreeSpace ...

Upvotes: 2

bisht
bisht

Reputation: 51

my_str = "hello world"

Converting string to bytes

my_str_as_bytes = str.encode(my_str)

Converting bytes to string

my_decoded_str = my_str_as_bytes.decode()

Upvotes: 2

DAXaholic
DAXaholic

Reputation: 35378

You can remove the characters with translate like so

b'Caption FreeSpace ... \r\r\n\r\r\n'.translate(None, b'\r\n')

which results in

b'Caption FreeSpace Size C: 807194624 63869808640 D: Y: 216847310848 2748779065344 '  

If you know the encoding of the returned data you may want to use decode which will give you a string for further processing.
For example, assumed it is encoded in utf-8, you can just call decode with its default value and directly call split on it to split by white-space characters to get an array like this

b'Caption FreeSpace ... \r\r\n\r\r\n'.translate(None, b'\r\n').decode().split()  

Result

['Caption', 'FreeSpace', 'Size', 'C:', '807194624', '63869808640', 'D:', 'Y:', '216847310848', '2748779065344']

Upvotes: 1

Related Questions