Python 字符串格式化

Python 字符串 format() 方法能够按照指定的格式格式化输出字符串。

Python 字符串 format() 方法能够按照指定的格式格式化输出字符串。

通过在字符串中使用占位符 {} 来定义需要输出的格式,将指定的参数替换到相应的位置。

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

指定格式

还可以在占位符大括号内添加参数以指定单个值的格式.

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

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

多个值

如果由多个占位符,只需在 format() 方法按照顺序添加对应的参数。

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

输出:

I want 3 pieces of item number 567 for 49.00 dollars.

索引号

您可以使用索引号(大括号内的数字 {0} )来确保将值放置在正确的占位符中, 索引的值对应了参数的位置.

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

输出:

I want 3 pieces of item number 567 for 49.00 dollars.

带索引的占位符可以出现多次.

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

输出:

His name is John. John is 36 years old.

命名索引

可以通过在大括号内输入名称来使用命名索引 {carname} ,但是在传递参数值时必须使用名称 txt.format(carname = "Ford")

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

输出:

I have a Ford, it is a Mustang.