【问题标题】:Suppress/ print without b' prefix for bytes in Python 3在 Python 3 中抑制/打印不带 b' 前缀的字节
【发布时间】:2013-05-20 19:53:51
【问题描述】:

只是发布这个,以便我以后可以搜索它,因为它似乎总是难住我:

$ 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) 字符串,不带 b' 前缀?

【问题讨论】:

标签: python string python-3.x


【解决方案1】:

使用decode() 而不是encode() 将字节转换为字符串。

>>> import curses
>>> print(curses.version.decode())
2.2

【讨论】:

    【解决方案2】:

    就是这么简单... (这样,您可以对字典和列表字节进行编码,然后可以使用 json.dump / json.dumps 对其进行字符串化)

    你只需要使用base64

    import base64
    
    data = b"Hello world!" # Bytes
    data = base64.b64encode(data).decode() # Returns a base64 string, which can be decoded without error.
    print(data)
    

    默认情况下有些字节是不能解码的(图片就是例子),所以base64会把这些字节编码成可以解码成字符串的字节,取回字节就用

    data = base64.b64decode(data.encode())
    

    【讨论】:

      【解决方案3】:

      我有点晚了,但是对于 Python 3.9.1 这对我有用并删除了 -b 前缀:

      print(outputCode.decode())
      

      【讨论】:

        【解决方案4】:

        您可以使用此代码进行显示或打印:

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

        你可以用它来编码或保存:

        <str_object>.encode('utf-8')
        

        【讨论】:

          【解决方案5】:

          如果我们查看bytes.__repr__ 的源代码,它看起来好像b'' 已融入方法中。

          最明显的解决方法是从生成的repr() 中手动切掉b''

          >>> x = b'\x01\x02\x03\x04'
          
          >>> print(repr(x))
          b'\x01\x02\x03\x04'
          
          >>> print(repr(x)[2:-1])
          \x01\x02\x03\x04
          

          【讨论】:

          • 旁注:我不认为任何其他答案真正回答了这个问题。
          • 我想我会同意:您的解决方案,即repr(x)[2:-1],会生成一个str 对象,该对象将如愿打印。特别是,repr(b'\x01')[2:-1] 返回字符串\\x01,而decode() 将返回\x01,这与print() 不同。更明确地说,print(repr(b'\x01')[2:-1]) 将打印 \x01print(b'\x01'.decode()) 不会打印任何内容。
          • 另外,print(repr(b"\x01".decode())) 将打印 '\x01'(包含单引号的字符串),以便 print(repr(b"\x01".decode())[1:-1]) 打印 \x01(不包含单引号的字符串)。
          【解决方案6】:

          使用decode:

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

          【讨论】:

          • @jamylak 提醒它可以接受参数
          • 默认怎么做,我的意思是,默认使用utf-8不好吗?我不想每次打印时都使用.decode('utf-8')
          • 创建自定义打印
          • 一定要检查curses.version 不是None
          【解决方案7】:

          如果数据是 UTF-8 兼容格式,您可以将字节转换为字符串。

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

          如果数据尚未与 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
          

          【讨论】:

            【解决方案8】:

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

            sys.stdout.buffer.write(data)
            

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

            【讨论】:

              猜你喜欢
              • 2022-04-25
              • 2015-05-30
              • 2020-03-18
              • 2016-12-10
              • 1970-01-01
              • 2010-10-20
              • 2020-11-22
              相关资源
              最近更新 更多