Python Format Usage

  • python

posted on 13 May 2018 under category 人生经验

常见用法

print "{:.2f}".format(3.1415926) #3.14,保留小数点后两位
print "{:+.2f}".format(3.1415926) #+3.14 带符号保留小数点后两位
print "{:+.2f}".format(-10) #-10.00 带符号保留小数点后两位
print "{:+.0f}".format(-10.00) #-10  不带小数
print "{:0>2d}".format(1) #01 数字补零 (填充左边, 宽度为2)
print "{:x<2d}".format(1) #1x 数字补x (填充右边, 宽度为4)
print "{:x<4d}".format(10) #10xx 数字补x (填充右边, 宽度为4)
print "{:,}".format(1000000) #1,000,000 以逗号分隔的数字格式
print "{:.2%}".format(0.12) #12.00% 百分比格式
print "{:.2e}".format(1000000) #1.00e+06 指数记法
print "{:<10d}".format(10) #10 左对齐 (宽度为10)
print "{:>10d}".format(10) #        10 右对齐 (默认, 宽度为10)
print "{:^10d}".format(10) #    10 中间对齐 (宽度为10)

格式符

‘f’表示浮点数

‘d’表示十进制整数. 将数字以10为基数进行输出

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

‘e’表示幂符号. 用科学计数法打印数字, 用’e’表示幂.

对齐与填充

^、<、>分别是居中、左对齐、右对齐,后面带宽度

:后面带填充字符,只能是一个字符,不指定的话默认就是空格。