Python 3 bytes formatting

前端 未结 6 815
情书的邮戳
情书的邮戳 2020-12-05 22:41

In Python 3, one can format a string like:

\"{0}, {1}, {2}\".format(1, 2, 3)

But how to format bytes?

b\"{0}, {1}, {2}\".fo         


        
相关标签:
6条回答
  • 2020-12-05 22:52

    For Python 3.6+ you can use this nice and clean syntax:

    f'foo {bar}'.encode() # a byte string
    
    0 讨论(0)
  • 2020-12-05 23:02

    And as of 3.5 % formatting will work for bytes, too!

    https://mail.python.org/pipermail/python-dev/2014-March/133621.html

    0 讨论(0)
  • 2020-12-05 23:02

    Interestingly .format() doesn't appear to be supported for byte-sequences; as you have demonstrated.

    You could use .join() as suggested here: http://bugs.python.org/issue3982

    b", ".join([b'1', b'2', b'3'])
    

    There is a speed advantage associated with .join() over using .format() shown by the BDFL himself: http://bugs.python.org/msg180449

    0 讨论(0)
  • 2020-12-05 23:05

    Another way would be:

    "{0}, {1}, {2}".format(1, 2, 3).encode()
    

    Tested on IPython 1.1.0 & Python 3.2.3

    0 讨论(0)
  • 2020-12-05 23:13

    I found the %b working best in Python 3.6.2, it should work both for b"" and "":

    print(b"Some stuff %b. Some other stuff" % my_byte_or_unicode_string)
    
    0 讨论(0)
  • 2020-12-05 23:14

    I've found this to work.

    a = "{0}, {1}, {2}".format(1, 2, 3)
    
    b = bytes(a, encoding="ascii")
    
    >>> b
    b'1, 2, 3'
    
    0 讨论(0)
提交回复
热议问题