Python 格式化输出
%s :格式化成字符串,%.5s 可以指定截取几个字符,%5s 可以指定占位符宽度 ( 左缩进 ),%-5s 可以指定占位符宽度 ( 右缩进 )
In [1]: 'My name is %s' % 'Tom' Out[1]: 'My name is Tom' In [2]: 'My name is %.2s' % 'Tom' Out[2]: 'My name is To' In [3]: 'My name is %5s' % 'Tom' Out[3]: 'My name is Tom' In [4]: 'My name is %-5s' % 'Tom' Out[4]: 'My name is Tom '
%d :格式化成整数 ( 十进制 )
In [4]: 'My age is %d' % 20 Out[4]: 'My age is 20' In [5]: 'My age is %d' % 20.234 Out[5]: 'My age is 20'
%f :格式化成浮点数,%.5f 可以指定小数点后保留的位数
In [6]: 'My age is %f' % 20 Out[6]: 'My age is 20.000000' In [7]: 'My age is %.3f' % 20 Out[7]: 'My age is 20.000'
%g :指定保留几位有效的数字,默认保留6位有效数字
In [12]: 'This num is %g' % 1234.5678 Out[12]: 'This num is 1234.57' In [13]: 'This num is %.3g' % 1234.5678 Out[13]: 'This num is 1.23e+03' In [14]: 'This num is %.5g' % 1234.5678 Out[14]: 'This num is 1234.6'