在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方法,如何对字节进行格式化或“重写”?
发布于 2014-03-28 08:06:30
从Python3.5开始,%格式化也将适用于bytes!
这是PEP 461的一部分,由伊桑·福尔曼撰写:
PEP: 461
Title: Adding % formatting to bytes and bytearray
Version: $Revision$
Last-Modified: $Date$
Author: Ethan Furman <ethan at stoneleaf.us>
Status: Draft
Type: Standards Track
Content-Type: text/x-rst
Created: 2014-01-13
Python-Version: 3.5
Post-History: 2014-01-14, 2014-01-15, 2014-01-17, 2014-02-22, 2014-03-25,
2014-03-27
Resolution:
Abstract
========
This PEP proposes adding % formatting operations similar to Python 2's ``str``
type to ``bytes`` and ``bytearray`` [1]_ [2]_.
Rationale
=========
While interpolation is usually thought of as a string operation, there are
cases where interpolation on ``bytes`` or ``bytearrays`` make sense, and the
work needed to make up for this missing functionality detracts from the overall
readability of the code.
Motivation
==========
With Python 3 and the split between ``str`` and ``bytes``, one small but
important area of programming became slightly more difficult, and much more
painful -- wire format protocols [3]_.
This area of programming is characterized by a mixture of binary data and
ASCII compatible segments of text (aka ASCII-encoded text). Bringing back a
restricted %-interpolation for ``bytes`` and ``bytearray`` will aid both in
writing new wire format code, and in porting Python 2 wire format code.
Common use-cases include ``dbf`` and ``pdf`` file formats, ``email``
formats, and ``FTP`` and ``HTTP`` communications, among many others.PEP461是accepted by Guido van Rossum on March 27, 2014
已接受。恭喜组织了另一场相当有争议的讨论,并容忍了我在最后一分钟的笨拙!
由此,我们可以明显地得出结论,%不再计划被弃用(正如在Python3.1中宣布的那样)。
发布于 2014-01-09 21:20:18
另一种方法是:
"{0}, {1}, {2}".format(1, 2, 3).encode()在IPython 1.1.0和Python3.2.3上测试
发布于 2013-03-30 04:05:29
有趣的是,字节序列似乎不支持.format();正如您所演示的那样。
您可以按照这里的建议使用.join():http://bugs.python.org/issue3982
b", ".join([b'1', b'2', b'3'])与使用.format()相比,.join()有一个速度上的优势,BDFL自己展示了:http://bugs.python.org/msg180449
https://stackoverflow.com/questions/15710515
复制相似问题