Python 3 字节格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15710515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:44:49  来源:igfitidea点击:

Python 3 bytes formatting

pythonpython-3.xstring-formatting

提问by Ecir Hana

In Python 3, one can format a string like:

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

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

But how to format bytes?

但是如何格式化字节?

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

raises AttributeError: 'bytes' object has no attribute 'format'.

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

If there is no formatmethod for bytes, how to do the formatting or "rewriting" of bytes?

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

采纳答案by Ecir Hana

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

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

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

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

回答by mechanical_meat

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

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

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

您可以.join()按照此处的建议使用: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

BDFL 本人展示了与.join()过度使用相关的速度优势.format()http://bugs.python.org/msg180449

回答by Schcriher

Another way would be:

另一种方法是:

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

Tested on IPython 1.1.0 & Python 3.2.3

在 IPython 1.1.0 和 Python 3.2.3 上测试

回答by ivan_bilan

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

我发现%b在 Python 3.6.2 中效果最好,它应该适用于 b"" 和 "":

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

回答by binny

I've found this to work.

我发现这有效。

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

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

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