Suppress / print without b prefix for bytes in Python 3

Just post this so I can find it later, as it always stuns 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 a question: how to print a binary ( bytes ) string in Python 3 without the b' prefix?

+83
python string
May 25 '13 at 9:14
source share
4 answers

Use decode :

 print(curses.version.decode()) # 2.2 
+85
May 25 '13 at 9:14
source share

If bytes already use the appropriate character encoding; You can 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 
+16
May 25 '13 at 10:56
source share

If the data is in UTF-8 compatible format, you can convert the bytes to a string.

 >>> import curses >>> print(str(curses.version, "utf-8")) 2.2 

If desired, first convert to hexadecimal if the data is not yet compatible with UTF-8. For example, when the data is actual raw bytes.

 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 
+6
Mar 19 '18 at 10:59
source share

If we look at the source for bytes.__repr__ , it will look like b'' baked in a method.

The most obvious workaround is to manually cut b'' from the resulting repr() :

 >>> x = b'\x01\x02\x03\x04' >>> print(x) b'\x01\x02\x03\x04' >>> print(repr(x)[2:-1]) \x01\x02\x03\x04 
+1
Jul 29 '19 at 6:41
source share



All Articles