[Python]格式化输出(2)

Python版本:Python 2.7.13rc1

1.数字

整型

正确的写法:

>>> print 'The value of PI is approximately %d ' % (3)
The value of PI is approximately 3 
>>> print 'The value of PI is approximately {:d} '.format(3)
The value of PI is approximately 3 
>>> print 'The value of PI is approximately %d ' % (3.1415926)
The value of PI is approximately 3 

错误的写法:

>>> print 'The value of PI is approximately {:d} '.format(3.1415926)

对齐:

>>> print '%4d'%(42)
  42
>>> print '{:_>4d}'.format(42)
__42
>>> print '%04d'%(42)
0042
>>> print '{:04d}'.format(42)
0042

浮点型

>>> import math
>>> print 'The value of PI is approximately %f ' % (math.pi)
The value of PI is approximately 3.141593 
>>> print 'The value of PI is approximately {:f} '.format(math.pi)
The value of PI is approximately 3.141593

保留小数点后三位:

>>> print 'The value of PI is approximately %.3f ' % (math.pi)
The value of PI is approximately 3.142 
>>> print 'The value of PI is approximately {:.3f} '.format(math.pi)
The value of PI is approximately 3.142  

显示六个字符,其中包括小数点和小数点后三位,不足六个字符补0:

>>> print 'The value of PI is approximately %06.3f ' % (math.pi)
The value of PI is approximately 03.142 
>>> print 'The value of PI is approximately {:06.3f} '.format(math.pi)
The value of PI is approximately 03.142 

有正负号的数字

>>> print '%+d' % (42)
+42
>>> print '{:+d}'.format(42)
+42
>>> print '% d' % (-42)
-42
>>> print '{: d}'.format(-42)
-42
>>> print '% d' % (42)
 42
>>> print '{: d}'.format(42)
 42
>>> print '{:=5d}'.format((-42))
-  42

2.Dict类型的格式化输出

根据key取value:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> print '%(Sjoerd)d %(Jack)d %(Dcab)d' % table
4127 4098 7678
>>> print '{Sjoerd} {Jack} {Dcab}'.format(**table)
4127 4098 7678
>>> print '{t[Sjoerd]} {t[Jack]} {t[Dcab]}'.format(t=table)
4127 4098 7678

Dict遍历:

>>> for name, ID in table.items():
    print '{0:10} ==> {1:10d}'.format(name,ID)

Dcab       ==>       7678
Jack       ==>       4098
Sjoerd     ==>       4127
>>> for name, ID in table.items():
    print '{1:<10d} ==> {0:>10}'.format(name,ID)

7678       ==>       Dcab
4098       ==>       Jack
4127       ==>     Sjoerd

List 取值:

>>> table2 = ["Sjoerd","Jack","Dcab"]
>>> print '{t[0]} {t[2]}'.format(t=table2)
Sjoerd Dcab

3.输出对象的属性值

>>> class Plant(object):
    type = 'tree'
    kinds = [{'name':'oak'},{'name':'maple'}]


>>> print '{p.type}: {p.kinds[0][name]}'.format(p=Plant())
tree: oak

4.Datetime

>>> from datetime import datetime
>>> dt = datetime(2001, 2, 3, 4, 5)
>>> print '{:%Y-%m-%d %H:%M}'.format(dt)
2001-02-03 04:05
>>> print '{:{dfmt} {tfmt}}'.format(dt, dfmt='%Y-%m-%d', tfmt='%H:%M')
2001-02-03 04:05

5.参数化的格式

设置参数精度:

>>> print '%.*s = %.*f' % (3, 'Gibberish', 3, 2.7182)
Gib = 2.718
>>> print '{:.{prec}} = {:.{prec}f}'.format('Gibberish', 2.7182, prec=3)
Gib = 2.718

参数位置:

>>> print '{:{}{sign}{}.{}}'.format(2.7182818284, '>', 10, 3, sign='+')
     +2.72

6.重写format类

>>> class HAL9000(object):

    def __format__(self, format):
        if (format == 'open-the-pod-bay-doors'):
            return "I'm afraid I can't do that."
        return 'HAL 9000'

>>> print '{:open-the-pod-bay-doors}'.format(HAL9000())
I'm afraid I can't do that.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值