天天看点

Python天天美味(5) - ljust rjust center

Python中打印字符串时可以调用ljust(左对齐),rjust(右对齐),center(中间对齐)来输出整齐美观的字符串,使用起来非常简单,包括使用第二个参数填充(默认为空格)。看下面的例子就会明白了:

Python天天美味(5) - ljust rjust center

print '|','*'.ljust(10),'|'

Python天天美味(5) - ljust rjust center

print '|','*'.ljust(10,'-'),'|'

Python天天美味(5) - ljust rjust center

print '|','*'.rjust(10,'-'),'|'

Python天天美味(5) - ljust rjust center

print '|','*'.center(10,'-'),'|'

Python天天美味(5) - ljust rjust center
Python天天美味(5) - ljust rjust center

for a in range(1, 6):

Python天天美味(5) - ljust rjust center

    print 'a = '.ljust(5), repr(a).ljust(10), 'b = '.ljust(5), repr(a * 2)

输出结果:

Python天天美味(5) - ljust rjust center

| *          |

Python天天美味(5) - ljust rjust center

| *--------- |

Python天天美味(5) - ljust rjust center

| ---------* |

Python天天美味(5) - ljust rjust center

| ----*----- |

Python天天美味(5) - ljust rjust center

a =   1          b =   2

Python天天美味(5) - ljust rjust center

a =   2          b =   4

Python天天美味(5) - ljust rjust center

a =   3          b =   6

Python天天美味(5) - ljust rjust center

a =   4          b =   8

Python天天美味(5) - ljust rjust center

a =   5          b =   10

...

本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/02/1179709.html,如需转载请自行联系原作者