我想寫通過這個文檔測試功能:如何在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
備註:使用'for i in range(1,11):'代替while循環。 – 2011-05-18 05:08:22
備註2:爲什麼*需要*左對齊,當右對齊更容易且更易讀時? – 2011-05-18 05:09:40