python中強(qiáng)大的format函數(shù)實(shí)例詳解
python中format函數(shù)用于字符串的格式化
自python2.6開始,新增了一種格式化字符串的函數(shù)str.format(),此函數(shù)可以快速處理各種字符串。
語法
它通過{}和:來代替%。
請(qǐng)看下面的示例,基本上總結(jié)了format函數(shù)在python的中所有用法
#通過位置 print '{0},{1}'.format('chuhao',20) print '{},{}'.format('chuhao',20) print '{1},{0},{1}'.format('chuhao',20) #通過關(guān)鍵字參數(shù) print '{name},{age}'.format(age=18,name='chuhao') class Person: def __init__(self,name,age): self.name = name self.age = age def __str__(self): return 'This guy is {self.name},is {self.age} old'.format(self=self) print str(Person('chuhao',18)) #通過映射 list a_list = ['chuhao',20,'china'] print 'my name is {0[0]},from {0[2]},age is {0[1]}'.format(a_list) #my name is chuhao,from china,age is 20 #通過映射 dict b_dict = {'name':'chuhao','age':20,'province':'shanxi'} print 'my name is {name}, age is {age},from {province}'.format(**b_dict) #my name is chuhao, age is 20,from shanxi #填充與對(duì)齊 print '{:>8}'.format('189') # 189 print '{:0>8}'.format('189') #00000189 print '{:a>8}'.format('189') #aaaaa189 #精度與類型f #保留兩位小數(shù) print '{:.2f}'.format(321.33345) #321.33 #用來做金額的千位分隔符 print '{:,}'.format(1234567890) #1,234,567,890 #其他類型 主要就是進(jìn)制了,b、d、o、x分別是二進(jìn)制、十進(jìn)制、八進(jìn)制、十六進(jìn)制。 print '{:b}'.format(18) #二進(jìn)制 10010 print '{:d}'.format(18) #十進(jìn)制 18 print '{:o}'.format(18) #八進(jìn)制 22 print '{:x}'.format(18) #十六進(jìn)制12
總結(jié)
以上所述是小編給大家介紹的python中強(qiáng)大的format函數(shù)實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
如何通過Python的pyttsx3庫將文字轉(zhuǎn)為音頻
pyttsx3是一個(gè)開源的Python文本轉(zhuǎn)語音庫,可以將文本轉(zhuǎn)換為自然的人類語音,這篇文章主要介紹了如何通過Python的pyttsx3庫將文字轉(zhuǎn)為音頻,需要的朋友可以參考下2023-04-04Python在for循環(huán)中更改list值的方法【推薦】
這篇文章主要介紹了Python在for循環(huán)中更改list值的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-08-08C++通過內(nèi)嵌解釋器調(diào)用Python及間接調(diào)用Python三方庫
本文主要介紹了C++通過內(nèi)嵌解釋器調(diào)用Python及間接調(diào)用Python三方庫,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-12-12Python寫的Discuz7.2版faq.php注入漏洞工具
這篇文章主要介紹了Python寫的Discuz7.2版faq.php注入漏洞工具,全自動(dòng)的一款注入工具,針對(duì)Discuz7.2版,需要的朋友可以參考下2014-08-08Python爬蟲實(shí)現(xiàn)網(wǎng)頁信息抓取功能示例【URL與正則模塊】
這篇文章主要介紹了Python爬蟲實(shí)現(xiàn)網(wǎng)頁信息抓取功能,涉及Python使用URL與正則模塊針對(duì)網(wǎng)頁信息的讀取與匹配相關(guān)操作技巧,需要的朋友可以參考下2017-05-05Python自定義類的數(shù)組排序?qū)崿F(xiàn)代碼
這篇文章主要介紹了Python自定義類的數(shù)組排序?qū)崿F(xiàn)代碼,需要的朋友可以參考下2016-08-08