python format
程序员文章站
2022-04-04 20:53:43
...
format语法
基本插入语法
# default arguments
print("Hello {}, your balance is {}.".format("Adam", 230.2346))
# positional arguments
print("Hello {0}, your balance is {1}.".format("Adam", 230.2346))
# keyword arguments
print("Hello {name}, your balance is {blc}.".format(name="Adam", blc=230.2346))
# mixed arguments
print("Hello {0}, your balance is {blc}.".format("Adam", blc=230.2346)
输入字符格式化
类型 | 意义 |
---|---|
d | 整型 |
c | 字符 |
b | 二进制 |
o | 十进制 |
x | 十六进制小写字母 |
X | 十六进制大写字母 |
% | 百分数,放置%在其后 |
f | 浮点数,默认精度为6 |
e | 科学计数法(小写e表示) |
E | 科学计数法(大写E表示) |
文本对齐
类型 | 意义 |
---|---|
< | 向左对齐 |
> | 右向对齐 |
= | 符号位于最左 |
^ | 居中对齐 |
# integer numbers with right alignment
print("{:5d}".format(12))
# float numbers with center alignment
print("{:^10.3f}".format(12.2346))
# integer left alignment filled with zeros
print("{:<05d}".format(12))
# float numbers with center alignment
print("{:=8.3f}".format(-12.2346))
12
12.235
12000
- 12.235
动态格式化
# dynamic string format template
string = "{:{fill}{align}{width}}"
# passing format codes as arguments
print(string.format('cat', fill='*', align='^', width=5))
# dynamic float format template
num = "{:{align}{width}.{precision}f}"
# passing format codes as arguments
print(num.format(123.236, align='<', width=8, precision=2))
**cat**
123.24