Python 字串格式化(Python IO)

veelion發表於2019-03-03

利用print函式把資訊列印到顯示器,是我們程式設計中經常使用的功能。為了讓列印的資訊更容易讀懂,就需要更好的格式來列印。Python提供了記住不同的格式化輸出的方法。推薦的方法就是:f-字串str.format()函式。

Python字串格式化

f-字串(f-string)

格式化的字串字面值(簡稱為f-字串),是在字串的開始引號之前加上一個fF。在這樣的字串中,我們可以在花括號{}中引用變數或Python表示式。

比如:

In [34]: site = '猿人學Python'

In [35]: url = 'https://www.yuanrenxue.com/'

In [36]: f'The url of {site} is : {url}'
Out[36]: 'The url of 猿人學Python is : https://www.yuanrenxue.com/'

In [37]: a, b = 10, 20

In [38]: f'the sum of {a} and {b} is {a+b}'
Out[38]: 'the sum of 10 and 20 is 30'

花括號{}裡面的表示式可以有一些格式說明符,它們用來更好的控制值的格式化方式。比如下面這個例子,將浮點數保留到小數點後三位:

In [39]: pi = 3.1415926

In [40]: f'pi is {pi:0.3f}'
Out[40]: 'pi is 3.142'

上面這個f-字串中的表示式,在:後面跟了限制小數點位數的格式說明符0.3f

再比如下面這個限制最小字元寬度的,可以讓輸出保持列對齊:

In [41]: persons = {'Tom': 23, 'Jack': 29, 'William': 20}

In [42]: for name, age in persons.items(): 
    ...:     print(f'{name:10} : {age:5}') 
    ...:
Tom        :    23
Jack       :    29
William    :    20

str.format() 方法

字串本身提供的格式化方法format的基本用法如下:

In [53]: print('I am learning {} with {}'.format('Python', '猿人學'))
I am learning Python with 猿人學

從這個例子中我們可以看到,字串裡面的花括號被format方法傳入的引數替換,所以,花括號的數量應該和傳遞給format的引數的數量保持一致,嚴格來說,花括號的數量不能多於format傳遞的引數的數量,否則會報錯:

In [54]: print('I am learning {} with {}'.format('Python'))
---------------------------------------------------------------------------
IndexError          Traceback (most recent call last)
<ipython-input-54-11a586fa5126> in <module>
----> 1 print('I am learning {} with {}'.format('Python'))

IndexError: tuple index out of range

In [55]: print('I am learning {} with '.format('Python', '猿人學'))
I am learning Python with 

花括號中可以包含數字,用來表示傳遞給format()方法的物件的位置:

In [59]: print('{0} and {1}'.format('猿人學', 'Python'))
猿人學 and Python

In [60]: print('{1} and {0}'.format('猿人學', 'Python'))
Python and 猿人學

如果在format()方法中使用關鍵字引數,則使用引數的名稱來引用它們的值:

In [62]: print('{name} is {age} years old'.format( 
    ...: name='Tom', age=23))
Tom is 23 years old

當然,位置和關鍵字引數可以組合在一起使用:

In [63]: print('the {0} of {1}, {name} is {age} years old'.format('story', 'Tom', 
    ...: name='Tom', age=23))
the story of Tom, Tom is 23 years old

我們可以給format傳遞一個字典和使用方括號[]來訪問鍵來完成格式化:

In [80]: persons = {'Tom': 23, 'Jack': 29, 'William': 20}

In [81]: print('Tom:{0[Tom]:d}, Jack:{0[Jack]}, William:{0[William]:d}'.format(persons))   
Tom:23, Jack:29, William:20

其中花括號裡面的0[Tom]:d的意思是,0代表傳給format的第一個物件,即persons[Tom]就是通過鍵來引用第一個物件中Tom對應的值,即23:d是整數格式化說明符,如果Tom得到值是字串就會報錯:Unknown format code 'd' for object of type 'str'

這裡也可以使用**符合將字典作為關鍵字引數傳遞:

In [82]: print('Tom:{Tom:d}, Jack:{Jack}, William:{William:d}'.format(**persons))          
Tom:23, Jack:29, William:20

利用format方法,我們可以方便的生成一個整數和它的平方以及立方的表:

In [84]: for i in range(1, 10): 
    ...:     print('{0:2d} {1:3d} {2:3d}'.format(i, i*i, i*i*i)) 
    ...:
 1   1   1
 2   4   8
 3   9  27
 4  16  64
 5  25 125
 6  36 216
 7  49 343
 8  64 512
 9  81 729

手動格式化字串

字串物件str除了str.format()方法可以格式化外,還提供了一些方法進行格式化,比如:

str.rjust() 通過在左側填充空格來對給定寬度的欄位中的字串進行右對齊,同樣的,str.ljust()就是左對齊,str.center()就是中間對齊。

In [89]: 'abcd'.rjust(6)
Out[89]: '  abcd'

In [90]: 'abcd'.rjust(3)
Out[90]: 'abcd'

如果字串的長度小於rjust()傳遞的值,就會在其左側填充空格,並返回新的字串;如果字串的長度大於或等於rjust()傳遞的值,就不會做任何改變,原樣返回字串。

另外還有一個方法:str.zfill(),它會在字串左邊填充零,對於數字字串它能識別正負號:

In [90]: 'abcd'.rjust(3)
Out[90]: 'abcd'

In [91]: 'abc'.zfill(10)
Out[91]: '0000000abc'

In [92]: '-3.14'.zfill(10)
Out[92]: '-000003.14'

In [93]: '12'.zfill(10)
Out[93]: '0000000012'

In [94]: '+12'.zfill(10)
Out[94]: '+000000012'

舊的字串格式:%格式化方法

在Python 2中,使用百分號%進行格式化,跟C語言中的sprintf()非常相似。但在Python3中,更推薦使用str.format()方法或f-字串格式化。所以這裡就不再多講%格式化的內容。

總結與練習

在Python3中,推薦使用兩種字串格式化的方法:str.format()f-string格式化。分別練習如何使用這兩種方法。

猿人學banner宣傳圖

我的公眾號:猿人學 Python 上會分享更多心得體會,敬請關注。

***版權申明:若沒有特殊說明,文章皆是猿人學 yuanrenxue.com 原創,沒有猿人學授權,請勿以任何形式轉載。***

相關文章