Python字符串格式化

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


字符串格式()

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

有时,您无法控制文本的某些部分,它们可能来自数据库或用户输入?

{}要控制这些值,请在文本中 添加占位符(大括号),并通过以下format()方法运行这些值:

例子

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

price = 49
txt = "The price is {} dollars"
print(txt.format(price))
自己试试 »

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

例子

将价格格式化为带两位小数的数字:

txt = "The price is {:.2f} dollars"
自己试试 »

查看我们的String format() Reference中的所有格式类型。


多个值

如果要使用更多值,只需在 format() 方法中添加更多值:

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

并添加更多占位符:

例子

quantity = 3
itemno = 567
price = 49
myorder = "I want {} pieces of item number {} for {:.2f} dollars."
print(myorder.format(quantity, itemno, price))
转载于:

posted on 2022-03-28 12:24  -G  阅读(44)  评论(0)    收藏  举报

导航