如何将“二进制字符串”转换为Python3中的普通字符串?

时间:2021-01-09 18:26:02

For example, I have a string like this(return value of subprocess.check_output):

例如,我有一个这样的字符串(subprocess.check_output的返回值):

>>> b'a string'
b'a string'

Whatever I did to it, it is always printed with the annoying b' before the string:

不管我对它做了什么,它总是在字符串之前用烦人的b打印出来:

>>> print(b'a string')
b'a string'
>>> print(str(b'a string'))
b'a string'

Does anyone have any ideas about how to use it as a normal string or convert it into a normal string?

有没有人知道如何将它作为一个普通的字符串或者将它转换成一个普通的字符串?

2 个解决方案

#1


154  

Decode it.

解码。

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

要从字符串获取字节,对其进行编码。

>>> 'a string'.encode('ascii')
b'a string'

#2


26  

If the answer from falsetru didn't work you could also try:

如果谎言的答案不奏效,你也可以试试:

>>> b'a string'.decode('utf-8')
'a string'

#1


154  

Decode it.

解码。

>>> b'a string'.decode('ascii')
'a string'

To get bytes from string, encode it.

要从字符串获取字节,对其进行编码。

>>> 'a string'.encode('ascii')
b'a string'

#2


26  

If the answer from falsetru didn't work you could also try:

如果谎言的答案不奏效,你也可以试试:

>>> b'a string'.decode('utf-8')
'a string'