在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方法,如何格式化或"重写"字节?

推荐答案

从Python3.5开始,%种格式也适用于bytes种格式!

这是伊桑·弗曼(Ethan Furman)所著《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.

PEP 461为accepted by Guido van Rossum on March 27, 2014:

认可的.祝贺你,又一个相当有争议的问题

从这一点上,我们可以明显地得出结论,%不再是预定的弃用版本(正如在Python3.1中宣布的那样).

Python-3.x相关问答推荐

使用pythonnet和nicegui时无法pickle December对象

类型注释:pathlib. Path vs importlib. resources. abc. Traversable

替换Pandas中组下的列值

是什么原因导致Pandas=2.1.4和Pandas=1.4.2之间Pandas DataFrame中从Float64到int32的连续列转换方式不同

Django 3.2/Django-cms 3.11:查找错误:型号帐户.客户用户未注册

数据类对象列表的字典获取方法-在数据类列表中查找具有特定变量值的数据类

如何将参数/值从测试方法传递给pytest的fixture函数?

Pandas 根据条件增加Dataframe列

当我在正则表达式末尾使用斜杠时,为什么会得到不同的结果?

获取字符串中的两个工作日之间的差异

为什么 return node.next 会返回整个链表?

找到操作系统的图片文件夹的 CLI

使用大型多个数据集,其中每个数据集包含多个值 - Pytorch

具有 2 个输入的 python 3 map/lambda 方法

Generic[T] 基类 - 如何从实例中获取 T 的类型?

Python 类型提示语法如何/为什么起作用?

Pylint 给我最后的新行丢失

try 注释散列变量时,ABCMeta对象不可下标

将 Python 字节转换为无符号 8 位整数

如何将python日志(log)级别名称转换为整数代码