第一次聽說格式化,是清理電腦磁盤時,以為格式化就是清空一切,重回自由,後來才知道,格式化,是另一種妥協。
以下部分節選自《編寫高質量代碼:改善Python程序的91個建議》一書,需要該書電子版的可以私我。
第一部分:%操作符
%操作符根據轉換說明符所規定的格式返回一串格式化後的字符串,轉換說明符的基本形式為:
%[轉換標記][寬度[.精確度]]轉換類型
其中常見的轉換標記和轉換類型分別如圖1和圖2所示。如果未指定寬度,則默認輸出為字符串本身的寬度。
%操作符格式化字符串時常見用法:
1)直接格式化字符或者數值。
<code>print('your sorce is %06.1f' % 9.5) # your sorce is 0009.5/<code>
2)以元組的形式格式化。
<code>import math item_name = 'circumference' radius = 3 print('the %s of a circle with radius %f is %0.3f' % (item_name, radius, math.pi*radius*2)) # the circumference of a circle with radius 3.000000 is 18.850/<code>
3)以字典的形式格式化。
<code>item_dict = {'itemname': 'circumference', 'radius': 3, 'value': math.pi*radius*2} print('the %(itemname)s of a circle with radius %(radius)f is %(value)0.3f' % item_dict) # the circumference of a circle with radius 3.000000 is 18.850/<code>
第二部分:.format方法
.format方式格式化字符串的基本語法:
[[填充符]對齊方式][符號][#][0][寬度][,][.精確度][轉換類型]。
其中填充符可以是除了“{”和“}”符號之外的任意符號,對齊方式和符號分別如圖3和圖4所示。轉換類型跟%操作符的轉換類型類似,可以參見圖2。
.format方法幾種常見的用法如下:
1)使用位置符號。
<code>print('The number {0:,} in hex is: {0: #x}, the number {1} in oct is {1:#o}'.format(4746,45)) # The number 4,746 in hex is: 0x128a, the number 45 in oct is 0o55/<code>
其中{0}表示forma方法中對應的第一個參數,{1}表示format方法對應的第二個參數,依次遞推
2)使用名稱。
<code>print('the max number is {max}, the min number is {min}, the average number is {average:0.3f}'.format(max=189, min=12.6, average=23.5)) # the max number is 189, the min number is 12.6, the average number is 23.500/<code>
3)通過屬性。
<code>class Customer(object): def __init__(self, name, gender, phone): self.name = name self.gender = gender self.phone = phone # 通過str()函數返回格式化的結果 def __str__(self): return 'Customer({self.name},{self.gender},{self.phone})'.format(self=self) print(str(Customer('Lisa','Female','67889'))) # Customer(Lisa,Female,67889)/<code>
4)格式化元組的具體項。
<code>point=(1,3) print('X:{0[0]};Y:{0[1]}'.format(point)) # X:1;Y:3/<code>
第三部分:結論
在瞭解了兩種字符串格式的基本用法後,我們發現還是要儘量使用format方式而不是%操作符來格式化字符串。
理由一:format方式在使用上較%操作符更為靈活。使用format方式時,參數的順序與格式化的順序不必完全相同。如:
<code>print('The number {1} in hex is:{1:#x}, the number {0} in oct is {0:#o}'.format(4746,45)) # The number 45 in hex is:0x2d, the number 4746 in oct is 0o11212/<code>
上例中格式化的順序為{1},{0},其對應的參數申明的順序卻相反,{1}與45對應,而用%方法需要使用字典形式才能達到同樣的目的。
理由二:format方式可以方便地作為參數傳遞。
<code>weather = [('Monday','rain'),('Tuesday','sunny'),('Wednesday','sunny'),('Thursday','rain'),('Friday','cloudy')] formatter = "Weather of '{0[0]}' is '{0[1]}'".format for item in map(formatter, weather): print(item) #Weather of 'Monday' is 'rain' Weather of 'Tuesday' is 'sunny' Weather of 'Wednesday' is 'sunny' Weather of 'Thursday' is 'rain' Weather of 'Friday' is 'cloudy'/<code>
理由三:%最終會被.format方式所代替。這個理由可以認為是最直接的原因,在Python3.0中.format方法是推薦使用的方法,而之所以仍然保留%操作符是為了保持向後兼容。
理由四:%方法在某些特殊情況下使用時需要特別小心。
<code>item_name = ('mouse', 'mobilephone','cup') print('item_list are %s'%(item_name)) # 使用%方法格式化元組 # TypeError: not all arguments converted during string formatting print('item_list are %s'%(item_name,)) # 注意後面的逗號 # item_list are ('mouse', 'mobilephone', 'cup') print('item_list are {}'.format(item_name)) # 使用format方法直接格式化不會拋出異常 # item_list are ('mouse', 'mobilephone', 'cup')/<code>
該例子本意是把item_name看做一個整體來進行格式化,但直接使用時卻拋出TypeError,對於%直接格式化字符的這種形式,如果字符本身為元組,則需要使用在%使用(item_name,)這種形式才能避免錯誤,注意逗號。
關注微信公眾號“Python小鎮”,發現更多幹貨知識!