+4 votes
in Programming Languages by (14.7k points)
The output of one python function is a byte string (e.g. b'my string'). I want to convert it to a string. How can I remove b' prefix from the byte string?

1 Answer

0 votes
by (25.6k points)

You can try one of the following approaches to remove b' from a byte string. As a result, you will get a string.

Approach 1: Using decode() function

>>> t=subprocess.check_output('ls', shell=True)
>>> t
b'compress.py\n'
>>> b=t.decode('utf-8')
>>> b
'compress.py\n'

Approach 2: Using str() function

>>> t=subprocess.check_output('ls', shell=True)
>>> t
b'compress.py\n'
>>> a=str(t,'utf-8')
>>> a
'compress.py\n'

...