溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python的字符串格式化怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2023-05-04 09:51:54 來源:億速云 閱讀:113 作者:zzz 欄目:開發(fā)技術(shù)

這篇“Python的字符串格式化怎么實(shí)現(xiàn)”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python的字符串格式化怎么實(shí)現(xiàn)”文章吧。

為了確保字符串按預(yù)期顯示,我們可以使用 format() 方法對(duì)結(jié)果進(jìn)行格式化。

字符串 format()

format() 方法允許您格式化字符串的選定部分。

有時(shí)文本的一部分是你無法控制的,也許它們來自數(shù)據(jù)庫或用戶輸入?

要控制此類值,請(qǐng)?jiān)谖谋局刑砑诱嘉环ɑɡㄌ?hào) {}),然后通過 format() 方法運(yùn)行值:

實(shí)例

添加要顯示價(jià)格的占位符:

price = 52
txt = "The price is {} dollars"
print(txt.format(price))

運(yùn)行實(shí)例

Python的字符串格式化怎么實(shí)現(xiàn)

你可以在花括號(hào)內(nèi)添加參數(shù)以指定如何轉(zhuǎn)換值

實(shí)例

將價(jià)格格式化為帶有兩位小數(shù)的數(shù)字:

txt = "The price is {:.2f} dollars"

運(yùn)行實(shí)例

price = 52
txt = "The price is {:.2f} dollars"
print(txt.format(price))

Python的字符串格式化怎么實(shí)現(xiàn)

查看字符串 format() 參考手冊(cè)中的所有格式類型。

多個(gè)值

如需使用更多值,只需向 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í)例

Python的字符串格式化怎么實(shí)現(xiàn)

索引號(hào)

您可以使用索引號(hào)(花括號(hào) {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í)例

此外,如果要多次引用相同的值,請(qǐng)使用索引號(hào):

實(shí)例

age = 63
name = "Bill"
txt = "His name is {1}. {1} is {0} years old."
print(txt.format(age, name))

運(yùn)行實(shí)例

Python的字符串格式化怎么實(shí)現(xiàn)

命名索引

您還可以通過在花括號(hào) {carname} 中輸入名稱來使用命名索引,但是在傳遞參數(shù)值 txt.format(carname = “Ford”) 時(shí),必須使用名稱:

實(shí)例

myorder = "I have a {carname}, it is a {model}."
print(myorder.format(carname = "Porsche", model = "911"))

運(yùn)行實(shí)例

Python的字符串格式化怎么實(shí)現(xiàn)

以上就是關(guān)于“Python的字符串格式化怎么實(shí)現(xiàn)”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI