在 Python 3 中不带 b' 前缀的字节抑制/打印
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16748083/
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
Suppress/ print without b' prefix for bytes in Python 3
提问by sdaau
Just posting this so I can search for it later, as it always seems to stump me:
只是张贴这个以便我以后可以搜索它,因为它似乎总是让我难堪:
$ 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'"
As question: how to print a binary (bytes) string in Python 3, without the b'prefix?
作为问题:如何bytes在没有b'前缀的情况下在 Python 3 中打印二进制 ( ) 字符串?
回答by sdaau
Use decode:
使用decode:
print(curses.version.decode())
# 2.2
回答by jfs
If the bytes use an appropriate character encoding already; you could print them directly:
如果字节已经使用了适当的字符编码;你可以直接打印它们:
sys.stdout.buffer.write(data)
or
或者
nwritten = os.write(sys.stdout.fileno(), data) # NOTE: it may write less than len(data) bytes
回答by Frank
If the data is in an UTF-8 compatible format, you can convert the bytes to a string.
如果数据采用 UTF-8 兼容格式,则可以将字节转换为字符串。
>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2
Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.
如果数据尚未与 UTF-8 兼容,则可以选择先转换为十六进制。例如,当数据是实际的原始字节时。
from binascii import hexlify
from codecs import encode # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337
回答by Mateen Ulhaq
If we take a look at the source for bytes.__repr__, it looks as if the b''is baked into the method.
如果我们查看 的源代码bytes.__repr__,它看起来好像b''被烘焙到了方法中。
The most obvious workaround is to manually slice off the b''from the resulting repr():
最明显的解决方法是b''从结果中手动切片repr():
>>> x = b'\x01\x02\x03\x04'
>>> print(repr(x))
b'\x01\x02\x03\x04'
>>> print(repr(x)[2:-1])
\x01\x02\x03\x04

