kinght2008 发表于 2018-8-11 09:07:36

python格式输出

  http://my.oschina.net/dillan/blog/133877python输出格式化及函数format
  http://my.oschina.net/dillan/blog/133877Python中的字符串格式化
  1.Python中将两个整数相除,默认结果是为整数的。但我们可以通过下面的方法,使得两个整数相除的结果为小数。
http://blog.51cto.com/e/u/themes/default/images/spacer.giffrom__future__import division
http://blog.51cto.com/e/u/themes/default/images/spacer.gifprint7/3
  输出结果:
  2.3333333333
  2.format来实现百分比的数据输出:
  print (format(0.5236,'.2%'))
  >>>52.36%
  >>> print (format(0.52363,'0.2f'))
  0.52
  3.>>> mem = 87.345
  >>> print('输出百分比数字:%0.2f%%'%mem)
  输出百分比数字:87.34%
  4.
可以指定所需长度的字符串的对齐方式:< (默认)左对齐> 右对齐^ 中间对齐= (只用于数字)在小数点后进行补齐  >>> print format(1.125345,'0.2f')
  1.13
  >>> print format(1.125345,'10.2f')
  1.13
  >>> print format(1.125345,'<10.2f')
  1.13
  >>> print format(1.125345,'^10.2f')
  1.13
  >>> print '1:\t|{0:>10},'.format('wangyu')
  1:   | wangyu,
  >>> print '1:\t|{0:10},'.format('wangyu')
  1:   |wangyu ,
  5.
  可以使用decimal模块来设置计算的精度
>>> from decimal import *  
>>> print getcontext()
  
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999, capi
  
tals=1, flags=, traps=[Overflow, DivisionByZero, InvalidOperat
  
ion])
  
>>> print getcontext().prec
  
28
  
>>> getcontext().prec = 6
  
>>> Decimal(1) / Decimal(7)
  
Decimal('0.142857')
  
>>> getcontext().prec = 28
  
>>> Decimal(1) / Decimal(7)
  
Decimal('0.1428571428571428571428571429')
  6.
>>> round(float('23.123'),2)  
23.12
  
>>> '%.6f' % float('24.123')
  
'24.123000'
  
>>> print decimal.Decimal('%.6f' % float('24.123'))
  
24.123000
  7.
  round(flt, ndig=0) 接受一个浮点数 flt 并对其四舍五入,保存 ndig位小数。
>>> round(3.1415926,2)  
3.14
  
>>> round(3.1415926)#默认为0
  
3
  
>>> round(3.1415926,-2)
  
0.0
  
>>> round(3.1415926,-1)
  
0.0
  
>>> round(5.1415926,-1)
  
10.0
  
>>> round(314.15926,-1)
  
310.0
  其实就是调整小数点位置并根据调整后的小数点位置做四舍五入
页: [1]
查看完整版本: python格式输出