python3 中的b''解析

最近转换战场,可能要很长一段时间在windows上耕耘。在python掉windows cmd命令时,发现返回的是一串乱码,如发送dir命令,返回如下:

b' \xc7\xfd\xb6\xaf\xc6\xf7 D \xd6\xd0\xb5\xc4\xbe\xed\xc3\xbb\xd3\xd0\xb1\xea\xc7\xa9\xa1\xa3\r\n \xbe\xed\xb5\xc4\xd0\xf2\xc1\xd0\xba\xc5\xca\xc7 88E8-2AD2\r\n\r\n D:\\PyInvo \xb5\xc4\xc4\xbf\xc2\xbc\r\n\r\n2021/07/26  13:35    <DIR>  

 

即使使用最简单的执行echo。返回的也是一串带b''内容

b'xxx\r\n'

那么,这个b''是什么意思呢?

从官方文档中,我们看看

Firstly, the syntax for bytes literals is largely the same as that for string literals, except that a b prefix is added:
Single quotes: b'still allows embedded "double" quotes'
Double quotes: b"still allows embedded 'single' quotes".
Triple quoted: b'''3 single quotes''', b"""3 double quotes"""

是一个bytes,序列,说明见链接https://docs.python.org/3/library/stdtypes.html#bytes

 

 

需要怎么处理呢?

最简单的,如果包含文本,需要用对应的编码方式进行解码

如:

strvalue = bytesvalue.decode('utf-8')

 

 

参考文档:

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

https://docs.python.org/3/library/codecs.html#error-handlers

https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

posted @ 2021-07-26 13:48  Believer007  阅读(19151)  评论(0编辑  收藏  举报