輸入輸出
有幾種方法可以顯示程序的輸出;數據可以以人類可讀的形式打印出來,或者寫入文件以供將來使用。本章將討論一些可能性。
更漂亮的輸出格式
到目前為止,我們遇到了兩種寫入值的方法:表達式語句 和 print()
函數。(第三種是使用文件對象的 write()
方法;標准輸出文件可以作為 sys.stdout
引用。更多相關信息可參考python教程標准庫指南。)
通常,你需要更多地控制輸出的格式,而不僅僅是打印空格分隔的值。有幾種格式化輸出的方法。
-
要使用 格式字字符串字面值 ,請在字符串的開始引號或三引號之前加上一個
f
或F
。在此字符串中,你可以在{
和}
字符之間寫可以引用的變量或字面值的 Python 表達式。>>> year = 2016 >>> event = 'Referendum' >>> f'Results of the {year} {event}' 'Results of the 2016 Referendum'
-
字符串的
str.format()
方法需要更多的手動操作。你仍將使用{
和}
來標記變量將被替換的位置,並且可以提供詳細的格式化指令,但你還需要提供要格式化的信息。>>> yes_votes = 42_572_654 >>> no_votes = 43_132_495 >>> percentage = yes_votes / (yes_votes + no_votes) >>> '{:-9} YES votes {:2.2%}'.format(yes_votes, percentage) ' 42572654 YES votes 49.67%'
-
最后,你可以使用字符串切片和連接操作自己完成所有的字符串處理,以創建你可以想象的任何布局。字符串類型有一些方法可以執行將字符串填充到給定列寬的有用操作。
當你不需要花哨的輸出而只是想快速顯示某些變量以進行調試時,可以使用 repr()
or str()
函數將任何值轉化為字符串。
str()
函數是用於返回人類可讀的值的表示,而 repr()
是用於生成解釋器可讀的表示(如果沒有等效的語法,則會強制執行 SyntaxError
)對於沒有人類可讀性的表示的對象, str()
將返回和 repr()
一樣的值。很多值使用任一函數都具有相同的表示,比如數字或類似列表和python字典的結構。特殊的是字符串有兩個不同的表示。
幾個例子:
>>> s = 'Hello, world.' >>> str(s) 'Hello, world.' >>> repr(s) "'Hello, world.'" >>> str(1/7) '0.14285714285714285' >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' >>> print(s) The value of x is 32.5, and y is 40000... >>> # The repr() of a string adds string quotes and backslashes: ... hello = 'hello, world\n' >>> hellos = repr(hello) >>> print(hellos) 'hello, world\n' >>> # The argument to repr() may be any Python object: ... repr((x, y, ('spam', 'eggs'))) "(32.5, 40000, ('spam', 'eggs'))"
string
模塊包含一個 Template
類,它提供了另一種將值替換為字符串的方法,使用類似 $x
的占位符並用字典中的值替換它們,但對格式的控制要少的多。
格式化字符串文字
格式化字符串字面值 (常簡稱為 f-字符串)能讓你在字符串前加上 f
和 F
並將表達式寫成 {expression}
來在字符串中包含 Python 表達式的值。
可選的格式說明符可以跟在表達式后面。這樣可以更好地控制值的格式化方式。以下示例將pi舍入到小數點后三位:
>>> import math >>> print(f'The value of pi is approximately {math.pi:.3f}.') The value of pi is approximately 3.142.
在 ':'
后傳遞一個整數可以讓該字段成為最小字符寬度。這在使列對齊時很有用。:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} >>> for name, phone in table.items(): ... print(f'{name:10} ==> {phone:10d}') ... Sjoerd ==> 4127 Jack ==> 4098 Dcab ==> 7678
其他的修飾符可用於在格式化之前轉化值。 '!a'
應用 ascii()
,'!s'
應用 str()
,還有 '!r'
應用 repr()
:
>>> animals = 'eels' >>> print(f'My hovercraft is full of {animals}.') My hovercraft is full of eels. >>> print(f'My hovercraft is full of {animals!r}.') My hovercraft is full of 'eels'.
有關這些格式規范的參考,請參閱參考指南 Format Specification Mini-Language。
字符串的 format() 方法
str.format()
方法的基本用法如下所示:
>>> print('We are the {} who say "{}!"'.format('knights', 'Ni')) We are the knights who say "Ni!"
花括號和其中的字符(稱為格式字段)將替換為傳遞給 str.format()
方法的對象。花括號中的數字可用來表示傳遞給 str.format()
方法的對象的位置。
>>> print('{0} and {1}'.format('spam', 'eggs')) spam and eggs >>> print('{1} and {0}'.format('spam', 'eggs')) eggs and spam
如果在 str.format()
方法中使用關鍵字參數,則使用參數的名稱引用它們的值。:
>>> print('This {food} is {adjective}.'.format( ... food='spam', adjective='absolutely horrible')) This spam is absolutely horrible.
位置和關鍵字參數可以任意組合:
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')) The story of Bill, Manfred, and Georg.
如果你有一個非常長的格式字符串,你不想把它拆開,那么你最好按名稱而不是位置引用變量來進行格式化。這可以通過簡單地傳遞字典和使用方括號 '[]'
訪問鍵來完成:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; ' ... 'Dcab: {0[Dcab]:d}'.format(table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678
這也可以通過使用 '**' 符號將表作為關鍵字參數傳遞。:
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} >>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)) Jack: 4098; Sjoerd: 4127; Dcab: 8637678
這在與內置函數 vars()
結合使用時非常有用,它會返回包含所有局部變量的字典。
例如,下面幾行代碼生成一組整齊的列,其中包含給定的整數和它的平方以及立方:
>>> for x in range(1, 11): ... print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) ... 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 10 100 1000
關於使用 str.format()
進行字符串格式化的完整概述,請參閱 Format String Syntax 。
手動格式化字符串
這是同一個平方和立方的表,手動格式化的:
>>> for x in range(1, 11): ... print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ') ... # Note use of 'end' on previous line ... print(repr(x*x*x).rjust(4)) ... 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 10 100 1000
(注意每列之間的一個空格是通過使用 print()
的方式添加的:它總是在其參數間添加空格。)
字符串對象的 str.rjust()
方法通過在左側填充空格來對給定寬度的字段中的字符串進行右對齊。類似的方法還有 str.ljust()
和 str.center()
。這些方法不會寫入任何東西,它們只是返回一個新的字符串,如果輸入的字符串太長,它們不會截斷字符串,而是原樣返回;這雖然會弄亂你的列布局,但這通常比另一種方法好,后者會在顯示值時可能不准確(如果你真的想截斷,你可以添加一個切片操作,例如 x.ljust(n)[:n]
。)
還有另外一個方法,str.zfill()
,它會在數字字符串的左邊填充零。它能識別正負號:
>>> '12'.zfill(5) '00012' >>> '-3.14'.zfill(7) '-003.14' >>> '3.14159265359'.zfill(5) '3.14159265359'
舊的字符串格式化方法
%
操作符也可以用作字符串格式化。它將左邊的參數解釋為一個很像 sprintf()
風格 的格式字符串,應用到右邊的參數,並返回一個由此格式化操作產生的字符串。例如:
>>> import math >>> print('The value of pi is approximately %5.3f.' % math.pi) The value of pi is approximately 3.142.
可在 printf-style String Formatting 部分找到更多信息。