format 函数包含_Python成为专业人士笔记-高级对象Format格式化
“專業(yè)人士筆記”系列目錄:
創(chuàng)帆云:Python成為專業(yè)人士筆記--強(qiáng)烈建議收藏!每日持續(xù)更新!?zhuanlan.zhihu.com在存儲(chǔ)和轉(zhuǎn)換數(shù)據(jù)輸出供查看時(shí),字符串格式可能變得非常重要。Python提供了本文概述的各種字符串格式化方法
基礎(chǔ)字符串格式化
foo = 1bar = 'bar'baz = 3.14可以使用str.format來格式化輸出。括號(hào)對(duì)里按傳遞參數(shù)的順序進(jìn)行替換:
foo = 1 bar = 'bar' baz = 3.14print('{}, {} and {}'.format(foo, bar, baz)) #輸出: "1, bar and 3.14"還可以在括號(hào)內(nèi)指定索引。下面的這些數(shù)字對(duì)應(yīng)于傳遞給str.format函數(shù)(從0開始)的參數(shù)的順序
foo = 1 bar = 'bar' baz = 3.14 print('{0}, {1}, {2}, and {1}'.format(foo, bar, baz)) #輸出: "1, bar, 3.14, and bar"print('{0}, {1}, {2}, and {3}'.format(foo, bar, baz)) #:報(bào)錯(cuò) index out of range error 參數(shù)中并沒有也可以使用命名參數(shù) :
print("X value is: {x_val}. Y value is: {y_val}.".format(x_val=2, y_val=3)) #輸出: "X value is: 2. Y value is: 3."對(duì)象屬性可以在傳遞到str.format中進(jìn)行引用:
class AssignValue(object):def __init__(self, value):self.value = value #這里定義了value對(duì)象屬性my_value = AssignValue(6) print('My value is: {.value}'.format(my_value)) #將對(duì)象作為參數(shù)傳入后,可以使用.value訪問對(duì)象的values屬性當(dāng)然也可以使用字典傳入并引用鍵,注意其引用的寫法:
my_dict = {'key': 6, 'other_key': 7} print("My other key is: {[key]}".format(my_dict))#輸出:My other key is: 6list列表和tuple元組,都一樣的引用:
my_list = ['zero', 'one', 'two'] print("2nd element is: {[2]}".format(my_list))#輸出:2nd element is: two除了參數(shù)索引之外,還可以在花括號(hào)中包含格式規(guī)范。這是一個(gè)表達(dá)式,它遵循特殊的規(guī)則,并且必須在前面加上冒號(hào)(:)。有關(guān)格式規(guī)范的完整描述,請(qǐng)參閱文檔。格式規(guī)范的一個(gè)例子是對(duì)齊指令: ~^20(其中^代表以中心對(duì)齊,兩邊都填充~字符, 總長(zhǎng)度為20 )
print(‘{:~^20}’.format(‘centered’))
#輸出:~~centered~~
由于format是一個(gè)函數(shù),所以它可以用作其他函數(shù)的參數(shù) :
number_list = [12, 45, 78] print(list(map('the number is {}'.format, number_list))) # 輸出: ['the number is 12', 'the number is 45', 'the number is 78']from datetime import datetime, timedeltaonce_upon_a_time = datetime(2010, 7, 1, 12, 0, 0) delta = timedelta(days=13, hours=8, minutes=20)gen = (once_upon_a_time + x * delta for x in range(5))print('n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen)))# 輸出: 2010-07-01 12:00:00 # 2010-07-14 20:20:00 # 2010-07-28 04:40:00 # 2010-08-10 13:00:00 # 2010-08-23 21:20:00用 f 格式化文本
foo = 'bar' print(f'Foo is {foo}')#輸出:Foo is bar# 這也適用于更高級(jí)的格式字符串,包括對(duì)齊和點(diǎn)符號(hào)print(f'{foo:^7s}') #輸出:bar格式字符串也可以嵌套 :
price = 478.23 print(f"{f'${price:0.2f}':*>20s}")#輸出:**************$478.23Float 格式化
print('{:.0f}'.format(42.12345)) #42print('{:.1f}'.format(42.12345)) #42.1函數(shù)作為命令參數(shù)時(shí)的引用方式:
print('{a:.3f}'.format(a=42.12345,b=232)) #42.123浮點(diǎn)數(shù)也可以用科學(xué)計(jì)算符號(hào)或百分?jǐn)?shù)來格式化:
print('{:.3e}'.format(42.12345)) #4.212e+01print('{:.0%}'.format(42.12345)) #4212%你還可以組合使用{0}和{name}符號(hào)。當(dāng)您希望用一個(gè)聲明將所有變量四舍五入到預(yù)先指定的小數(shù)位數(shù)時(shí),這尤其有用 :
s = 'Hello' a, b, c = 1.12345, 2.34567, 34.5678 digits = 2print('{0}! {1:.{n}f}, {2:.{n}f}, {3:.{n}f}'.format(s, a, b, c, n=digits))#輸出:Hello! 1.12, 2.35, 34.57命名占位符
格式字符串可以包含命名占位符,這些占位符通過使用關(guān)鍵字參數(shù)進(jìn)行格式轉(zhuǎn)化,先看下面的例子:
#使用字典作為內(nèi)置format_map函數(shù)的參數(shù) data = {'first': 'zhou', 'last': 'fan!'} print('{first} {last}'.format_map(data))#輸出:zhou fan!#使用命名空間作為內(nèi)置format函數(shù)(注意不是format_map) 的參數(shù) print('{first} {last}'.format(first='zhou',last='fan'))#輸出:zhou fan因此,內(nèi)置format_map函數(shù)允許使用字典而無需先解析它
datatime格式的字符串
任何類都可以通過format方法配置自己的字符串格式語法。標(biāo)準(zhǔn)Python庫中可以方便地使用這種格式的一種類型是:datetime類型,在這種類型中可以直接在str.format中使用等效于strftime的格式化代碼
from datetime import datetime print('North America: {dt:%m/%d/%Y}. ISO: {dt:%Y-%m-%d}.'.format(dt=datetime.now()))#輸出:North America: 05/19/2020. ISO: 2020-05-19.Numerical格式化
format()方法可以將數(shù)字解析成不同的格式,例如 :
print('{:c}'.format(65))# 解析成Unicode 字符print('{:b}'.format(10))# 解析成二進(jìn)制#輸出: A 1010利用類自定義格式化
注意:下面的所有內(nèi)容都適用于str.format方法以及format函數(shù)。在下面的文本中,兩者是可以互換的
對(duì)于傳遞給format函數(shù)的每個(gè)值,Python都會(huì)為該參數(shù)尋找一個(gè)__format__方法。因此,你完全可以自定義類的__format__方法來確定format函數(shù)將如何顯示和格式化類及其屬性
但是,其實(shí)現(xiàn)與str方法的實(shí)現(xiàn)完全不同,因?yàn)樵赺_format__方法中,你可以考慮以什么樣的方式格式化對(duì)象,包括對(duì)齊方式、字段寬度等,甚至(如果你愿意的話)實(shí)現(xiàn)自己的格式說明符和自己的格式化語言擴(kuò)展
舉例:
class Example(object):def __init__(self, a, b, c):self.a, self.b, self.c = a, b, cdef __format__(self, format_spec):""" 實(shí)現(xiàn)“s”格式說明符的特殊語義 """# 拒絕任何不是s的格式化字符if format_spec[-1] != 's':raise ValueError('{} 不理解的格式說明符 ',format_spec[:-1])# 本例中的輸出將是(<a>,<b>,<c>) raw = "(" + ",".join([str(self.a), str(self.b), str(self.c)]) + ")"# 通過使用內(nèi)建的字符串格式來重建格式語言 # 因?yàn)槲覀冎涝几袷揭?guī)范以“s”結(jié)尾 # 我們可以利用上面構(gòu)造的string參數(shù)來使用str.format方法 return "{r:{f}}".format(r=raw, f=format_spec)inst = Example(1, 2, 3) print("{:>20s}".format(inst)) # 輸出 : (1,2,3) # 請(qǐng)注意如何使用右對(duì)齊和字段寬度20的格式化串以上所有代碼均已在python3云環(huán)境中調(diào)試通過
禁止轉(zhuǎn)載
總結(jié)
以上是生活随笔為你收集整理的format 函数包含_Python成为专业人士笔记-高级对象Format格式化的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 防弹衣杀手:FN-57手枪?
- 下一篇: 四指指虎绳子绑法教程