[Python] 格式化输出(1)

Python版本:Python 2.7.13rc1

1.基本格式化输出

Old style:%

>>> print 'We are the %s who say "%s"!' % ('knights','Hi')
We are the knights who say "Hi"!

New style:str.format() method

>>> print 'We are the {} who say "{}"!'.format('knights','Hi')
We are the knights who say "Hi"!
>>> print 'We are the {1} who say "{0}"! So {other}'.format('knights','Hi',other='great.')
We are the Hi who say "knights"! So great.

2.str() 和 repr()

>>> class Data(object):
    def __str__(self):
        return 'str'
    def __repr__(self):
        return 'repr'

Old style:

>>> print '%s %r' % (Data(),Data())
str repr

New Style:

>>> print '{0!s} {0!r}'.format(Data(),Data())
str repr

注意: %s和%r的区别

>>> print '1.%s2.%r' % ('Old\n','Old\n')
1.Old
2.'Old\n'

在上面这段代码中,使用%r后,转义字符就失去了作用,print出来的是写到代码里的原始字符串。%s用作显示,%r用作debug。


3.对齐

右对齐:

>>> print '! %20s' % ('test')
!                 test
>>> print '! {:>20}'.format('test')
!                 test

左对齐:

>>> print '%-20s !' % ('test')
test                 !
>>> print '{:20} !'.format('test')
test                 !

.format()可以加入填充字符:

>>> print '{:_<20} !'.format('test')
test________________ !
>>> print '! {:_>20}'.format('test')
! ________________test

4.截断长字符串

假设我们只需要显示5个字符:

>>> print 'It is %.5s !' % ('Goodstyle')
It is Goods !
>>> print 'It is {:.5} !'.format('Goodstyle')
It is Goods !

截断并对齐:

>>> print 'It is %-10.5s !' % ('Goodstyle')
It is Goods      !
>>> print 'It is {:<10.5} !'.format('Goodstyle')
It is Goods      !

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值