天天看點

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,如需轉載請自行聯系原作者