如何在 Python3 中将“二进制字符串”转换为普通字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17615414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert 'binary string' to normal string in Python3?
提问by Hanfei Sun
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?
有没有人对如何将其用作普通字符串或将其转换为普通字符串有任何想法?
采纳答案by falsetru
Decode it.
解码它。
>>> b'a string'.decode('ascii')
'a string'
To get bytes from string, encode it.
要从字符串中获取字节,请对其进行编码。
>>> 'a string'.encode('ascii')
b'a string'