Python入門教程(三十三)Python的字符串格式化
為了確保字符串按預(yù)期顯示,我們可以使用 format() 方法對結(jié)果進(jìn)行格式化。
字符串 format()
format()
方法允許您格式化字符串的選定部分。
有時文本的一部分是你無法控制的,也許它們來自數(shù)據(jù)庫或用戶輸入?
要控制此類值,請?jiān)谖谋局刑砑诱嘉环ɑɡㄌ?{}),然后通過 format() 方法運(yùn)行值:
實(shí)例
添加要顯示價格的占位符:
price = 52 txt = "The price is {} dollars" print(txt.format(price))
運(yùn)行實(shí)例
你可以在花括號內(nèi)添加參數(shù)以指定如何轉(zhuǎn)換值
實(shí)例
將價格格式化為帶有兩位小數(shù)的數(shù)字:
txt = "The price is {:.2f} dollars"
運(yùn)行實(shí)例
price = 52 txt = "The price is {:.2f} dollars" print(txt.format(price))
查看字符串 format() 參考手冊中的所有格式類型。
多個值
如需使用更多值,只需向 format() 方法添加更多值:
print(txt.format(price, itemno, count))
并添加更多占位符
實(shí)例
quantity = 3 itemno = 567 price = 52 myorder = "I want {} pieces of item number {} for {:.2f} dollars." print(myorder.format(quantity, itemno, price))
運(yùn)行實(shí)例
索引號
您可以使用索引號(花括號 {0} 內(nèi)的數(shù)字)來確保將值放在正確的占位符中:
實(shí)例
quantity = 3 itemno = 567 price = 52 myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars." print(myorder.format(quantity, itemno, price))
運(yùn)行實(shí)例
此外,如果要多次引用相同的值,請使用索引號:
實(shí)例
age = 63 name = "Bill" txt = "His name is {1}. {1} is {0} years old." print(txt.format(age, name))
運(yùn)行實(shí)例
命名索引
您還可以通過在花括號 {carname} 中輸入名稱來使用命名索引,但是在傳遞參數(shù)值 txt.format(carname = “Ford”) 時,必須使用名稱:
實(shí)例
myorder = "I have a {carname}, it is a {model}." print(myorder.format(carname = "Porsche", model = "911"))
運(yùn)行實(shí)例
到此這篇關(guān)于Python入門教程(三十三)Python的字符串格式化的文章就介紹到這了,更多相關(guān)Python字符串格式化內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中read,readline和readlines的區(qū)別案例詳解
這篇文章主要介紹了Python中read,readline和readlines的區(qū)別案例詳解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09Numpy實(shí)現(xiàn)矩陣運(yùn)算及線性代數(shù)應(yīng)用
這篇文章主要介紹了Numpy實(shí)現(xiàn)矩陣運(yùn)算及線性代數(shù)應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03