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 !