Suppress/ print without b' prefix for bytes in Python 3

前端 未结 5 873
野性不改
野性不改 2020-11-28 08:13

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 lin         


        
相关标签:
5条回答
  • 2020-11-28 08:47

    Use decode:

    print(curses.version.decode())
    # 2.2
    
    0 讨论(0)
  • 2020-11-28 08:51

    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
    
    0 讨论(0)
  • 2020-11-28 08:51

    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(b"\x13\x37"))
    b'1337'
    >>> print(str(hexlify(b"\x13\x37"), "utf-8"))
    1337
    >>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
    1337
    
    0 讨论(0)
  • 2020-11-28 08:52

    If we take a look at the source for bytes.__repr__, it looks as if the b'' is baked into the method.

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

    >>> x = b'\x01\x02\x03\x04'
    
    >>> print(repr(x))
    b'\x01\x02\x03\x04'
    
    >>> print(repr(x)[2:-1])
    \x01\x02\x03\x04
    
    0 讨论(0)
  • 2020-11-28 09:01

    you can use this code for showing or print :

    <byte_object>.decode("utf-8")
    

    and you can use this for encode or saving :

    <str_object>.encode('utf-8')
    
    0 讨论(0)
提交回复
热议问题