Python/gloss python string format

来自菜鸟教程
跳转至:导航、​搜索

<languages />

Python格式字符串

格式字符串

正如我们在“ Python变量”一章中了解到的那样,我们无法将字符串和数字组合如下:

  age = 36
txt = "My name is John, I am " + age
print(txt)

但是我们可以使用 format() 方法!

The format() 方法采用传递的参数,对其进行格式化,然后将其放置在占位符所在的字符串中 {} are:

使用 format() 将数字插入字符串的方法:

  age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

format()方法接受无限数量的参数,并放置在各自的占位符中:

  quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} 
  pieces of item {} for {} dollars."
print(myorder.format(quantity, 
  itemno, price))

您可以使用索引号 {0} 确保将参数放置在正确的占位符中:

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