string – Suppress/ print without b prefix for bytes in Python 3

string – Suppress/ print without b prefix for bytes in Python 3

Use decode:

print(curses.version.decode())
# 2.2

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

string – Suppress/ print without b prefix for bytes in Python 3

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

>>> 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.

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(bx13x37))
b1337
>>> print(str(hexlify(bx13x37), utf-8))
1337
>>>> print(str(encode(bx13x37, hex), utf-8))
1337

Leave a Reply

Your email address will not be published.