Eci*_*ana 44 python string-formatting python-3.x
在Python 3中,可以格式化一个字符串,如:
"{0}, {1}, {2}".format(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
但是如何格式化字节?
b"{0}, {1}, {2}".format(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
加油AttributeError: 'bytes' object has no attribute 'format'.
如果没有format字节方法,如何格式化或"重写"字节?
Eci*_*ana 36
从3.5 %格式也适用于bytes!
https://mail.python.org/pipermail/python-dev/2014-March/133621.html
小智 15
另一种方式是:
"{0}, {1}, {2}".format(1, 2, 3).encode()
Run Code Online (Sandbox Code Playgroud)
在IPython 1.1.0和Python 3.2.3上测试过
ber*_*nie 12
有趣的.format()是,字节序列似乎不支持; 正如你所展示的那样.
您可以.join()按照此处的建议使用:http://bugs.python.org/issue3982
b", ".join([b'1', b'2', b'3'])
Run Code Online (Sandbox Code Playgroud)
与BDFL本人所显示的.join()过度使用相关的速度优势.format():http://bugs.python.org/msg180449
iva*_*lan 10
我发现%b在 Python 3.6.2 中效果最好,它应该适用于 b"" 和 "":
print(b"Some stuff %b. Some other stuff" % my_byte_or_unicode_string)
Run Code Online (Sandbox Code Playgroud)
对于 Python 3.6+,您可以使用这种简洁明了的语法:
f'foo {bar}'.encode() # a byte string
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39409 次 |
| 最近记录: |