%操作符,左侧为需要格式化的字符串,右侧为对象。
>>>'That is %d %s bird!' % (1, 'dead')
That is 1 dead bird!
格式化允许将多个步骤合并为一个简单的操作:
>>>exclam = "Ni"
>>>"The knights who say %s!" % exclam
'The knights who say Ni!'
字符串格式化代码
代码(typecode) | 意义 |
---|---|
s | 字符串(或任何对象) |
r | s,但使用repr,而不是str |
c | 字符 |
d | 十进制(整数) |
i | 整数 |
u | 无符号(整数) |
o | 八进制整数 |
x | 十六进制整数 |
X | x,但打印大写 |
e | 浮点指数 |
E | e,但打印大写 |
f | 浮点十进制 |
F | 浮点十进制 |
g | 浮点e或f |
G | 浮点E或f |
% | 常量% |
通用结构:%[(name)][flags][width][.precision]typecode
flags | 左对齐(-);正负号(+);补零(0) |
---|---|
width | 数字位数 |
.precision | 小数点后的位数 |
>>>x = 1234
>>>res = "integeres: ...%d...%-6d...%06d" % (x, x, x)
>>>res #无格式...左对齐...补零
'integers: ...1234...1234 ...001234'
>>>x = 1.23456789
>>>'%e | %E | %f | %g' % (x, x, x, x)
'1.234568e+00 | 1.234568E+00 |1.234568 |1.23457'
>>>'%-6.2f | %05.2f | %+06.1f' % (x, x, x)
'1.23 | 01.23 | +001.2'
如果在运行时还不知道大小,可以在格式化字符串中用一个*来指定,从而迫使它们的值从%运算符右边的输出中的下一项获取:
>>>'%f, %.2f, %.*f' % (1/3.0, 1/3.0, 4, 1/3.0)#指定4位小数
'0.333333, 0.33, 0.3333'
基于字典的字符串格式化:
>>>"%(n)d %(x)s" % {"n":1, "x":"spm"}
'1 spam'
可以建立一个数值字典,一次性替换:
>>>reply = """
Greetings...
Hello %(name)s!
Your age is %(age)s
"""
>>>values = {'name':'Bob', 'age':40}
>>>print(reply % values)
Greetings...
Hello Bob!
Your age is 40
字符串格式化调用方法
字符串对象的format方法使用主体字符串作为模板,接受任意多个参数。在主体字符串中,花括号通过位置(如,{1})或关键字(如,{food})指出替换目标。
>>>'{0} eggs and {1}'.format(2, 'spam')
2 eggs and spam
#可以打乱顺序
>>>'{motto}, {0} and {food}'.format(42, motto=3.14, food=[1,2])
'3.14, 42 and [1,2]'