一般來說,我們希望更多的控制輸出格式,而不是簡單的以空格分割。這里有兩種方式:
第一種是由你自己控制。使用字符串切片、連接操作以及 string 包含的一些有用的操作。
第二種是使用str.format()方法。
下面給一個示例:
1 # 第一種方式:自己控制 2 for x in range(1, 11): 3 print(str(x).rjust(2), str(x*x).rjust(3), end=' ') 4 print(str(x*x*x).rjust(4)) 5 6 # 第二種方式:str.format() 7 for x in range(1, 11): 8 print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) 9 10 # 輸出都是: 11 # 1 1 1 12 # 2 4 8 13 # 3 9 27 14 # 4 16 64 15 # 5 25 125 16 # 6 36 216 17 # 7 49 343 18 # 8 64 512 19 # 9 81 729 20 # 10 100 1000
第一種方式中,字符串對象的 str.rjust() 方法的作用是將字符串靠右,並默認在左邊填充空格,類似的方法還有 str.ljust() 和 str.center() 。這些方法並不會寫任何東西,它們僅僅返回新的字符串,如果輸入很長,它們並不會截斷字符串。我們注意到,同樣是輸出一個平方與立方表,使用str.format()會方便很多。
str.format()的基本用法如下:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"
括號及括號里的字符將會被 format() 中的參數替換.。括號中的數字用於指定傳入對象的位置:
>>> print('{0} and {1}'.format('Kobe', 'James')) Kobe and James >>> print('{1} and {0}'.format('Kobe', 'James')) James and Kobe
如果在 format() 中使用了關鍵字參數,那么它們的值會指向使用該名字的參數:
>>> print('The {thing} is {adj}.'.format(thing='flower', adj='beautiful')) The flower is beautiful.
可選項':'和格式標識符可以跟着 field name,這樣可以進行更好的格式化:
>>> import math >>> print('The value of PI is {0:.3f}.'.format(math.pi)) The value of PI is 3.142.
在':'后傳入一個整數,可以保證該域至少有這么多的寬度,用於美化表格時很有用:
>>> table = {'Jack':4127, 'Rose':4098, 'Peter':7678} >>> for name, phone in table.items(): ... print('{0:10} ==> {1:10d}'.format(name, phone)) ... Peter ==> 7678 Rose ==> 4098 Jack ==> 4127
我們還可以將參數解包進行格式化輸出。例如,將table解包為關鍵字參數:
table = {'Jack':4127, 'Rose':4098, 'Peter':7678} print('Jack is {Jack}, Rose is {Rose}, Peter is {Peter}.'.format(**table)) # 輸出:Jack is 4127, Rose is 4098, Peter is 7678.
補充:
% 操作符也可以實現字符串格式化。它將左邊的參數作為類似 sprintf() 式的格式化字符串,而將右邊的代入:
1 import math 2 print('The value of PI is %10.3f.' %math.pi) 3 # 輸出:The value of PI is 3.142.
因為這種舊式的格式化最終會從Python語言中移除,應該更多的使用 str.format() 。
(本文轉載自腳本之家http://www.jb51.net/article/53849.htm#comments)