2011-05-18 74 views
0

我想寫通過這個文檔測試功能:如何在Python中左對齊列中的數字?

Prints a table of values for i to the power of 1,2,5 and 10 from 1 to 10 
left aligned in columns of width 4, 5, 8 and 13 
>>> print_function_table() 
i i*2 i*5 i*10 
1 1 1  1 
2 4 32  1024 
3 9 243  59049 
4 16 1024 1048576 
5 25 3125 9765625 
6 36 7776 60466176 
7 49 16807 282475249 
8 64 32768 1073741824 
9 81 59049 3486784401 
10 100 100000 10000000000 

我覺得我幾乎沒有,但我似乎無法左對齊我的專欄。

的代碼,我是:

def print_function_table(): 
    i = 1 
    s = "{:^4} {:^5} {:^8} {:^13}" 
    print s.format("i", "i*2", "i*5", "i*10") 
    while i <= 10: 
     print s.format(i, i*2, i*5, i*10) 
     i += 1 
+1

備註:使用'for i in range(1,11):'代替while循環。 – 2011-05-18 05:08:22

+1

備註2:爲什麼*需要*左對齊,當右對齊更容易且更易讀時? – 2011-05-18 05:09:40

回答

4

怎樣......

def print_function_table(): 
    s = "{:<4} {:<5} {:<8} {:<13}" 
    print s.format("i", "i*2", "i*5", "i*10") 
    for i in range(1,11): 
     print s.format(i, i**2, i**5, i**10) 

+1

注意:'「{} {}」.format()'從Python 3.1+開始有效;對於以前的版本,應該使用'「{0} {1}」。format()'(帶有顯式索引),請參閱http://docs.python.org/py3k/library/string.html第6.1.3.2節。 – 2011-10-26 13:51:13

+0

@Joël不是真的,現在的python 2.7.3 doc [也提到這個](http://docs.python.org/library/string.html#formatstrings)。 Py3k的功能喜歡回溯 – Kos 2012-06-23 10:46:45

+0

這將是更漂亮的eval而不是重複標題:) – 2012-07-13 19:42:55