python格式化输出之format用法

BUG之神 257

format()功能很强大,它把字符串当成一个模板,通过传入的参数进行格式化,并且使用大括号‘{}’作为特殊字符代替‘%’。

1、基本用法

  • (1)不带编号,即“{}”
  • (2)带数字编号,可调换顺序,即“{1}”、“{2}”
  • (3)带关键字,即“{a}”、“{tom}”
>>> print('{} {}'.format('苹果','教育')) # 不带字段
苹果 教育

>>> print('{0} {1}'.format('苹果','教育')) # 带数字编号
苹果 教育

>>> print('{0} {1} {0}'.format('苹果','教育')) # 打乱顺序
苹果 教育 苹果

>>> print('{1} {1} {0}'.format('苹果','教育'))
教育 教育 苹果

>>> print('{a} {b} {a}'.format(a='苹果',b='教育')) # 带关键字
苹果 教育 苹果

当大括号是字符串本身的一部分,用{{表示{

pi=3.14159
print("圆周率的近似值是:{{{}}}".format(pi))

输出:

圆周率的近似值是:{3.14159}

2、进阶用法

  • (1)< (默认)左对齐、> 右对齐、^ 中间对齐、
  • (2)取位数“{:4s}”、"{:.2f}"等
>>> print('{} and {}'.format('苹果','教育')) # 默认左对齐
苹果 and 教育

>>> print('{:10s} and {:>10s}'.format('苹果','教育')) # 取10位左对齐,取10位右对齐
苹果 and 教育

>>> print('{:^10s} and {:^10s}'.format('苹果','教育')) # 取10位中间对齐
苹果 and 教育

>>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数
1.123 is 1.12

>>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位
1.123 is 1.12
3、多个格式化
'b' - 二进制。将数字以2为基数进行输出。
>>> print('{0:b}'.format(3))
11

'c' - 字符。在打印之前将整数转换成对应的Unicode字符串。
>>> print('{:c}'.format(20))
4

'd' - 十进制整数。将数字以10为基数进行输出。
>>> print('{:d}'.format(20))
20

'o' - 八进制。将数字以8为基数进行输出。
>>> print('{:o}'.format(20))
24

'x' - 十六进制。将数字以16为基数进行输出,9以上的位数用小写字母。
>>> print('{:x}'.format(20))
14

'e' - 幂符号。用科学计数法打印数字。用'e'表示幂。
>>> print('{:e}'.format(20))
2.000000e+01

'g' - 一般格式。将数值以fixed-point格式输出。当数值特别大的时候,用幂形式打印。
>>> print('{:g}'.format(20.1))
20.1

'n' - 数字。当值为整数时和'd'相同,值为浮点数时和'g'相同。不同的是它会根据区域设置插入数字分隔符。
>>> print('{:f}'.format(20))
20.000000
>>> print('{:n}'.format(20))
20

'%' - 百分数。将数值乘以100然后以fixed-point('f')格式打印,值后面会有一个百分号。

>>> print('{:%}'.format(20))
2000.000000%

4、通过位置匹配参数

>>> '{0}, {1}, {2}'.format('北京', '苹果', '教育')
'北京,苹果,教育'
>>> '{}, {}, {}'.format('北京', '苹果', '教育') # 3.1+版本支持
'北京,苹果,教育'
>>> '{2}, {1}, {0}'.format('北京', '苹果', '教育')
'教育,苹果,北京'
>>> '{2}, {1}, {0}'.format(*'北京千') # 可打乱顺序
'千, 京, 北'
>>> '{0}{1}{0}'.format('苹果', '教育') # 可重复
'苹果教育苹果'


5、通过名字匹配参数
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'

另,可在字符串前加f以达到格式化的目的,在{}里加入对象,此为format的另一种形式:

name = 'zhangsan'
age = 18
sex = 'man'
job = "IT"
salary = 9999.99

print(f'my name is {name.capitalize()}.')
print(f'I am {age:*^10} years old.')
print(f'I am a {sex}')
print(f'My salary is {salary:10.3f}')

# 结果
my name is Zhangsan.
I am ****18**** years old.
I am a man
My salary is 9999.990

分享