Python 3字节格式化

时间:2013-03-29 19:54:47

标签: python python-3.x string-formatting

在Python 3中,可以格式化字符串,如:

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

但是如何格式化字节?

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

提出AttributeError: 'bytes' object has no attribute 'format'

如果字节没有format方法,如何格式化或“重写”字节?

6 个答案:

答案 0 :(得分:34)

从3.5 %开始格式化也适用于bytes

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

答案 1 :(得分:12)

另一种方式是:

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

在IPython 1.1.0& Python 3.2.3

答案 2 :(得分:11)

有趣的是.format()似乎不支持字节序列;正如你所展示的那样。

您可以按照http://bugs.python.org/issue3982

的建议使用.join()
b", ".join([b'1', b'2', b'3'])

.join()相比,使用BDFL自己显示的.format()有一个速度优势:http://bugs.python.org/msg180449

答案 3 :(得分:4)

对于Python 3.6+,您可以使用以下简洁的语法:

f'foo {bar}'.encode() # a byte string

答案 4 :(得分:3)

我发现%3.6在Python 3.6.2中运行得最好,它应该适用于b""和"":

print(b"Some stuff %b. Some other stuff" % my_byte_or_unicode_string)

答案 5 :(得分:-2)

我发现这行得通。

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

b = bytes(a, encoding="ascii")

>>> b
b'1, 2, 3'