Python ကွက် ပြောင်းလဲ

为了确保字符串按预期显示,我们可以使用 format() 方法对结果进行格式化。

字符串 format()

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

有时文本的一部分是你无法控制的,也许它们来自数据库或用户输入?

要控制此类值,请在文本中添加占位符(花括号 {}),然后通过 format() 方法运行值:

အမှတ်

添加要显示价格的占位符:

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

အမှတ်ပေးခြင်း

您可以在花括号内添加参数以指定如何转换值:

အမှတ်

သုံးပုံစံ တစ်ခု နှင့် နှစ်ချက် နှင့် ပြောင်းထည့်ပါ:

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

အမှတ်ပေးခြင်း

format() မီးရူး အသုံးပြုခြင်း နှင့် ပထမပေါ် ပြောင်းထည့်ပါ:

အခြား ကိန်းသိန်း

အခြား ကိန်းသိန်း အသုံးပြုရန် အသုံးပြုပါ format() မီးရူး အသုံးပြုပါ:

print(txt.format(price, itemno, count))

အသစ် တခုခု ပြောင်းထည့်ပါ:

အမှတ်

quantity = 3
itemno = 567
price = 52
myorder = "ကျေးရွား {} ပုံစံ {} ကို {:.2f} ဒေါ်လာ အတွက် လိုချင်ပါသည်"
print(myorder.format(quantity, itemno, price))

အမှတ်ပေးခြင်း

အမှတ်လက်တွေ

အမှတ်လက်တွေ ကို အသုံးပြုပါ။ {0} အချက်အလက် ကို သတ်မှတ်ပါ။

အမှတ်

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))

အမှတ်ပေးခြင်း

တခုခုတည်း အချက်အလက် ကို အသုံးပြုခြင်း လုံး အား ကြိုးစား သွားသင်း လို့ လျှင် အမှတ်လက်တွေ ကို အသုံးပြုပါ။

အမှတ်

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

အမှတ်ပေးခြင်း

အမည်ခံ လက်တွေ

မည်သည့် နှင့် နောက်ဆုံး အချက်အလက် ကို သတ်မှတ်ပါ။ {carname} အမည် ဖြင့် အမည်ခံ လက်တွေ အသုံးပြုခြင်း များ သာ ဖြစ်သည့် မှာ အမည် ဝေးကွား ကို သတ်မှတ်ပါ။ ဝေးကွား ကို ပေးပြီး အချက်အလက် ကို ပေးခြင်း txt.format(carname = "Ford") အခါ၌ အမည် အသုံးပြုပါ။

အမှတ်

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

အမှတ်ပေးခြင်း