str.format()是在python3中引入的字符串格式化方法,可以用来对字符串输出进行替换。其语法格式为:
{}.format(value)
例如单个字符串替换:
In [1]: print("{}, Is anybody in there?".format("hello"))
hello, Is anybody in there?
多个字符串替换,为顺序替换:
In [3]: print("{}, is anybody in {}".format("hello", "there"))
hello, is anybody in there
在{}里面定义使用format中值的顺序:
In [2]: print("{1} is an, {0}".format("ItchyHacker", "AI"))
AI is an, ItchyHacker
str中第一个{}为1, 第二个为0, 因此分别对应为"AI"和”ItchyHacker"
在{}中第一个替换值的key,并且在format中通过key指定值。
In [5]: print("{name} is an, {obj}".format(name="ItchyHacker", obj="AI"))
ItchyHacker is an, AI
通过在{}中使用占位符对输出进行定制:
输出数据类型的指定:
s – strings
d – decimal integers (base-10)
f – floating point display
c – character
b – binary
o – octal
x – hexadecimal with lowercase letters after 9
X – hexadecimal with uppercase letters after 9
e – exponent notation
例如:
In [7]: print("{name:s} is {height:f}m high, and weights {weight:d}kg".format(name="
...: ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.750000m high, and weights 70kg
指定输出的长度和使用占位符号:
数字: 输出占多少位
.数字: 保留小数点多少位
0数字: 以0为占位符号
身高用.2f限制输出小数点后两位,体重使用04d限制输出4位,同时使用0为占位符号。没有0的话就是空格作为占位符号。
In [8]: print("{name:s} is {height:.2f}m high, and weights {weight:04d}kg".format(na
...: me="ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.75m high, and weights 0070kg
指定对齐方式:
< : left-align text in the field
^ : center text in the field
> : right-align text in the field
体重右边对齐:
In [9]: print("{name:s} is {height:.2f}m high, and weights {weight:>6d}kg".format(na
...: me="ItchyHacker", height=1.75, weight=70))
ItchyHacker is 1.75m high, and weights 70kg