str.format()
Python2.6之后新增的一宗格式化字符串的函数。
用{}
和:
来替换以前的%
>>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world") # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world") # 设置指定位置
'world hello world'
%方式
%
是一种占位符。
符号 | 意义 |
---|---|
%s | 字符串 |
%d/%i | 十进制整数 |
%u | 过时的十进制表示 |
%o | 八进制 |
%x/%X | 十六进制整数 |
%f/%F | 浮点数 |
%e/%E | 科学计数法 |
%% | 输出% |
对于%%
,第一个%
起到转义的作用,使结果输出百分号%