這一篇主要記錄下 Python 的字符串輸出形式,來自 Cescfangs 的個人博客。
1. str
與repr
很多時候用 Python
進行輸出,我們會把其他類型的值轉化成string
進行輸出(私以為是Python
注重和人的交互,而string
是最適合與人類進行交互的數據類型),有str()
和repr()
兩種方法對數據類型進行轉化,str()
轉化后的結果更適合與人進行交互,而repr()
轉化后的結果則可以被Python
的解釋器閱讀,但當要轉化的對象沒有適合與人交互的類型時,str()
轉化的結果和repr()
是一樣的:
>>> s='hello world'
>>> str(s)
'hello world'
>>> repr(s)
"'hello world'"
>>>
當交互的對象是人時,'hello world'顯而易見就是一個字符串,字符串代表的意思是不言而喻,或者說人更關注' '內的信息,而非' '本身,但是機器則不同,如果直接把hello world傳給機器,他很難處理這個數據,但是有了' '后,Python
的解釋器就知道這是一個字符串,或者也可以這么說,相較于字符串的具體內容,機器更關心的是'hello world'這個整體,所以為了保存所需要的信息,repr()
會給轉化的對象加上" "。
>>> x=10
>>> s='the value of x is '+repr(x)
>>> s
'the value of x is 10'
>>> u='the value of x is '+str(x)
>>> u
'the value of x is 10'
>>>
對于這種組合類型的變量,str()
和repr()
的結果是一樣的。
>>> h='hello \n'
>>> print(str(h))
hello
>>> print(repr(h))
'hello \n'
>>>
str()
和repr()
的區別可見一斑。
2. 表格形式的輸出
>>> for x in range(11):
print(str(x).rjust(2), str(x * x).rjust(3), str(x**3).rjust(4))
0 0 0
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.rjust()
方法不會對該變量做任何處理。只是返回一個新的變量,字符的長度根據所給的參數確定,對齊方式為右對齊,多余的空間用空格補齊,類似的還有str.ljust()
,str.center()
等。當所給的長度小于字符串本身的長度時,這些方法不會截止數據,而是原封不動返回,這可能會破壞美觀,但是總比數據破壞要好吧?如果要強制截斷數據,可以用str().ljust(n)[:n]
這種形式:
>>> for x in range(11):
print(str(x).rjust(2), str(x * x).rjust(3), str(x**3).rjust(3)[:3])
0 0 0
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 100
還有一種str.zfill()
方法,與str.rjust()
不同,它補齊的是0而不是空格,而且它能夠理解正負號的意思:
>>> '123'.zfill(7)
'0000123'
>>> '-12.3'.zfill(7)
'-0012.3'
>>> '123456'.zfill(4)
'123456'
>>>
3. 格式化輸出
這是一種和C語言非常相似的輸出方法,但是個人覺得更加好用:
>>> print('{} is a {}'.format('Cescfangs', 'gooner'))
Cescfangs is a gooner
'{}'的內容會被format()
中的參數所替代,可以在'{}'里填上數字來指定format()
中的位置,但是如果'{}'里的是參數,其中的內容會以被format()
中的字符替換:
>>> print('{1} is a {0}'.format('Cescfangs', 'gooner'))
gooner is a Cescfangs
>>> print('{Ramsey} is a {gunner}'.format(Ramsey='Cescfangs', gunner='gooner'))
Cescfangs is a gooner
還可以用':'對輸出的范圍進行控制,我們輸出小數點后三位的$\pi$:
>>> print('value of pi is {0:.3f}'.format(math.pi))
value of pi is 3.142
':'可以起到固定位數輸出的作用,這會讓我們的輸出更加漂亮:
>>> arsenal = {'Ramsey': 16, 'Rosciky': 7, 'Chambers': 21, 'Ozil': 11}
>>> for player, number in arsenal.items():
print('{0:10}--->{1:3d}'.format(player, number))
Rosciky ---> 7
Ozil ---> 11
Ramsey ---> 16
Chambers ---> 21
未完待續