- Python兩種輸出值的方式: 表達式語句和 print() 函數。
- 第三種方式是使用檔案對象的 write() 方法,标準輸出檔案可以用 sys.stdout 引用。
- 如果你希望輸出的形式更加多樣,可以使用 str.format() 函數來格式化輸出值。
- 如果你希望将輸出的值轉成字元串,可以使用 repr() 或 str() 函數來實作。
- str(): 函數傳回一個使用者易讀的表達形式。
- repr(): 産生一個解釋器易讀的表達形式。
s='Hello, Runoob'
str(s)
'Hello, Runoob'
repr(s)
"'Hello, Runoob'"
# repr() 函數可以轉義字元串中的特殊字元
hello = 'hello, runoob\n'
hellos = repr(hello)
print(hellos)
'hello, runoob\n'
# repr() 的參數可以是 Python 的任何對象
x = 10 * 3.25
y = 200 * 200
repr((x, y, ('Google', 'Runoob')))
"(32.5, 40000, ('Google', 'Runoob'))"
for x in range(1, 11):
#每列間的空格由 print()添加,字元串對象的 rjust() 方法, 它可以将字元串靠右, 并在左邊填充空格。
# 注意前一行 'end' 的使用
print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
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
str.format()
的基本使用
str.format()
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
- 括号及其裡面的字元 (稱作格式化字段) 将會被 format() 中的參數替換。
- 在括号中的數字用于指向傳入對象在 format() 中的位置,如下所示:
print('{}網址: "{}!"'.format('菜鳥教程', 'www.runoob.com'))
菜鳥教程網址: "www.runoob.com!"
print('{0} 和 {1}'.format('Google', 'Runoob'))
print('{1} 和 {0}'.format('Google', 'Runoob'))
Google 和 Runoob
Runoob 和 Google
如果在 format() 中使用了關鍵字參數, 那麼它們的值會指向使用該名字的參數。
print('{name}網址: {site}'.format(name='菜鳥教程', site='www.runoob.com'))
菜鳥教程網址: www.runoob.com
位置及關鍵字參數可以任意的結合:
print('站點清單 {0}, {1}, 和 {other}。'.format('Google', 'Runoob',other='Taobao'))
站點清單 Google, Runoob, 和 Taobao。
'!a' (使用 ascii()), '!s' (使用 str()) 和 '!r' (使用 repr())
可以用于在格式化某個值之前對其進行轉化:
import math
print('常量 PI 的值近似為: {}。'.format(math.pi))
print('常量 PI 的值近似為: {!r}。'.format(math.pi))
常量 PI 的值近似為: 3.141592653589793。
常量 PI 的值近似為: 3.141592653589793。
可選項
':'
和格式辨別符可以跟着字段名。 這就允許對值進行更好的格式化。 下面的例子将 Pi 保留到小數點後三位:
import math
print('常量 PI 的值近似為 {0:.3f}。'.format(math.pi))
常量 PI 的值近似為 3.142。
在 '
:
' 後傳入一個整數, 可以保證該域至少有這麼多的寬度。 用于美化表格時很有用。
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
for name, number in table.items():
print('{0:10} ==> {1:10d}'.format(name, number))
Google ==> 1
Runoob ==> 2
Taobao ==> 3
如果你有一個很長的格式化字元串, 而你不想将它們分開, 那麼在格式化時通過變量名而非位置會是很好的事情。
最簡單的就是傳入一個字典, 然後使用方括号 '
[]
' 來通路鍵值 :
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
print('Runoob: {0[Runoob]:d}; Google: {0[Google]:d}; Taobao: {0[Taobao]:d}'.format(table))
Runoob: 2; Google: 1; Taobao: 3
也可以通過在 table 變量前使用 '
**
' 來實作相同的功能:
table = {'Google': 1, 'Runoob': 2, 'Taobao': 3}
print('Runoob: {Runoob:d}; Google: {Google:d}; Taobao: {Taobao:d}'.format(**table))
Runoob: 2; Google: 1; Taobao: 3
舊式字元串格式化
%
操作符也可以實作字元串格式化。它将左邊的參數作為類似 sprintf() 式的格式化字元串, 而将右邊的代入, 然後傳回格式化後的字元串. 例如:
import math
print('常量 PI 的值近似為:%5.3f。' % math.pi)
常量 PI 的值近似為:3.142。
因為 str.format() 比較新的函數, 大多數的 Python 代碼仍然使用 % 操作符。但是因為這種舊式的格式化最終會從該語言中移除, 應該更多的使用 str.format().
讀取鍵盤輸入
Python提供了 input() 置函數從标準輸入讀入一行文本,預設的标準輸入是鍵盤。
- input 可以接收一個Python表達式作為輸入,并将運算結果傳回。
st = input("請輸入:");
print ("你輸入的内容是: ", st)
請輸入:edw
你輸入的内容是: edw
讀和寫檔案
open() 将會傳回一個 file 對象,基本文法格式如下:
open(filename, mode)
- filename:filename 變量是一個包含了你要通路的檔案名稱的字元串值。
- mode:mode決定了打開檔案的模式:隻讀,寫入,追加等。所有可取值見如下的完全清單。這個參數是非強制的,預設檔案通路模式為隻讀(r)。
參見:檔案
pickle 子產品
python的pickle子產品實作了基本的資料序列和反序列化。
- 通過pickle子產品的序列化操作我們能夠将程式中運作的對象資訊儲存到檔案中去,永久存儲。
- 通過pickle子產品的反序列化操作,我們能夠從檔案中建立上一次程式儲存的對象。
基本接口:
pickle.dump(obj, file, [,protocol])
有了 pickle 這個對象, 就能對 file 以讀取的形式打開:
x = pickle.load(file)
- 注解:從 file 中讀取一個字元串,并将它重構為原來的python對象。
- file: 類檔案對象,有read()和readline()接口。
示例:
import pickle
# 使用pickle子產品将資料對象儲存到檔案
data1 = {'a': [1, 2.0, 3, 4+6j],
'b': ('string', u'Unicode string'),
'c': None}
selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)
output = open('data.pkl', 'wb')
# Pickle dictionary using protocol 0.
pickle.dump(data1, output)
# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)
output.close()
import pprint, pickle
#使用pickle子產品從檔案中重構python對象
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
[1, 2, 3, <Recursion on list with id=2568497906696>]
探尋有趣之事!