Python 格式化输出

格式化输出

https://www.cnblogs.com/fat39/p/7159881.html#tag2

%

字符串输出

%s
%10s——右对齐,占位符10位
%-10s——左对齐,占位符10位
%.2s——截取2位字符串
%10.2s——10位占位符,截取两位字符串

1 >>> print('%s' % 'hello world')  # 字符串输出
 2 hello world
 3 >>> print('%20s' % 'hello world')  # 右对齐,取20位,不够则补位
 4          hello world
 5 >>> print('%-20s' % 'hello world')  # 左对齐,取20位,不够则补位
 6 hello world         
 7 >>> print('%.2s' % 'hello world')  # 取2位
 8 he
 9 >>> print('%10.2s' % 'hello world')  # 右对齐,取2位
10         he
11 >>> print('%-10.2s' % 'hello world')  # 左对齐,取2位
12 he

浮点数输出

%f ——保留小数点后面六位有效数字
  %.3f,保留3位小数位
%e ——保留小数点后面六位有效数字,指数形式输出
  %.3e,保留3位小数位,使用科学计数法
%g ——在保证六位有效数字的前提下,使用小数方式,否则使用科学计数法
  %.3g,保留3位有效数字,使用小数或科学计数法

1 >>> print('%f' % 1.11)  # 默认保留6位小数
 2 1.110000
 3 >>> print('%.1f' % 1.11)  # 取1位小数
 4 1.1
 5 >>> print('%e' % 1.11)  # 默认6位小数,用科学计数法
 6 1.110000e+00
 7 >>> print('%.3e' % 1.11)  # 取3位小数,用科学计数法
 8 1.110e+00
 9 >>> print('%g' % 1111.1111)  # 默认6位有效数字
10 1111.11
11 >>> print('%.7g' % 1111.1111)  # 取7位有效数字
12 1111.111
13 >>> print('%.2g' % 1111.1111)  # 取2位有效数字,自动转换为科学计数法
14 1.1e+03

整数输出

%o —— oct 八进制
%d —— dec 十进制
%x —— hex 十六进制

nHex = 0xFF
>>> print("nHex = %x,nDec = %d,nOct = %o" %(nHex,nHex,nHex))
nHex = ff,nDec = 255,nOct = 377

format

{槽}.format

原文地址:https://www.cnblogs.com/xiaoxuesheng993/p/10958732.html