Python 格式化字符串
格式化字符串
我们在 Python 变量章节中学过,不能像这样将字符串和数字直接组合在一起:
例子 1
age = 36 txt = "My name is Bill, I am " + age print(txt)
但是我们可以通过使用 format()
方法来组合字符串和数字!
format()
方法会接收传入的参数,对它们进行格式化,并将它们放置在字符串中占位符 {}
的位置:
例子 2
使用 format()
方法将数字插入到字符串中:
age = 36 txt = "My name is Bill, and I am {}" print(txt.format(age))
format()
方法可以接受任意数量的参数,并将它们放置在相应的占位符中:
例子 3
quantity = 3 itemno = 567 price = 49.95 myorder = "I want {} pieces of item {} for {} dollars." print(myorder.format(quantity, itemno, price))
你可以使用索引号 {0}
来确保参数被放置在正确的占位符中:
例子 4
quantity = 3 itemno = 567 price = 49.95 myorder = "I want to pay {2} dollars for {0} pieces of item {1}." print(myorder.format(quantity, itemno, price))