前言
在前面的学习中我们已经接触过str.format()
的输出格式,本节中我们将进一步学习字符串打印输出的相关内容,并通过一系列的小例子感受使用str.format()
输出的便捷。
实践
我们先来定义两个变量:
animal = "cow"
item = "moon"
如果我们想用字符串拼接的方式输出"The cow jumped over the moon"这句话,那就需要用到下述代码:
print("The "+animal+" jumped over the "+item)
>>> The cow jumped over the moon
我们在前面提到过,使用str.format()
格式输出需要用到{}
占位符,只要保证{}
的个数与变量个数相同并且变量出现的顺序与我们预期的一致,那就能打印出我们想要的结果:
print("The {} jumped over the {}".format(animal, item))
>>> The cow jumped over the moon
这个例子中一共用到了两个变量,所以我们需要两个{}
占位符,同时第一个位置期望打印"cow"所以我们将变量animal放在第一个位置,第二个位置期望打印"moon",所以我们将变量item放在第二个位置。如果我们颠倒变量的顺序,那打印的内容也会随之改变:
print("The {} jumped over the {}".format(item, animal))
>>> The moon jumped over the cow
当然我们也可以通过索引指定当前占位符表示哪个变量,只需要将变量的位置索引填到{}
占位符内部即可:
print("The {0} jumped over the {1}".format(animal, item))
>>