在Python 3中禁止/打印没有b'前缀的字节

只是张贴这个,所以我可以稍后search它,因为它似乎总是让我陷害:

$ python3.2 Python 3.2 (r32:88445, Oct 20 2012, 14:09:50) [GCC 4.5.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import curses >>> print(curses.version) b'2.2' >>> print(str(curses.version)) b'2.2' >>> print(curses.version.encode('utf-8')) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'bytes' object has no attribute 'encode' >>> print(str(curses.version).encode('utf-8')) b"b'2.2'" 

作为问题:如何在Python 3中打印一个二进制( bytes )string,没有b'前缀?

使用decode

 >>> print(curses.version.decode('utf-8')) 2.2 

如果字节已经使用了适当的字符编码, 你可以直接打印它们:

 sys.stdout.buffer.write(data) 

要么

 nwritten = os.write(sys.stdout.fileno(), data) # NOTE: it may write less than len(data) bytes