Skip to main content
 首页 » 编程设计

python之python 的字符串格式中的 %a 是什么

2024年11月01日27me-sa

我有一个关于字符串格式的基本问题。我使用 python 2.7 和 3+ 进行编码

我知道 %s 用于字符或字符串

name = "John" 
print("Hello, %s!" % name)  

你好,约翰!

现在,如果我使用整数

name = 123 
print("Hello, %s!" % name) 

输出是你好,123!

当我确实想将它转换为字节时,就像这样

name = 123 
print(b"Hello, %s!" % name) 

在 python 2.7 中 它向我抛出一个错误,指出 %b 需要字节,或者一个实现 __bytes__ 的对象,而不是 'int'

name = 123 
print(b"Hello, %a!" % name) 

%a 是否明确用于获取字节类型的东西..我在网上找不到关于 %a 的太多信息..有人写的旧代码广泛使用它,我正在调试它..所以需要一些帮助来理解上面提到的(在转换为字节时使用字符串或数字)

请您参考如下方法:

来自 PEP 461 -- Adding % formatting to bytes and bytearray :

%a will give the equivalent of repr(some_obj).encode('ascii', 'backslashreplace') on the interpolated value. Use cases include developing a new protocol and writing landmarks into the stream; debugging data going into an existing protocol to see if the problem is the protocol itself or bad data; a fall-back for a serialization format; or any situation where defining __bytes__ would not be appropriate but a readable/informative representation is needed [6].

%r is included as a synonym for %a for the sole purpose of making 2/3 code bases easier to maintain. Python 3 only code use %a [7].