使用print()函数打印一个变量是一项简单的任务,但打印多个变量也不是一项复杂的任务。有多种方法来打印多个变量。
Python打印多个变量
要在Python中打印多个变量,可以使用print()函数。print(*objects)是一个内置的Python函数,它将*objects作为多个参数来打印由空格分隔的每个参数。
有很多方法可以打印多个变量。一个简单的方法是使用print()函数。
band = 8
name = "Sarah Fier"
print("The band for", name, "is", band, "out of 10")
输出
The band for Sarah Fier is 8 out of 10
在这段代码中,我们使用print()函数打印以下两个变量。
- 乐队
- 名称
在print()函数里面,我们把变量名放到了各自的位置上,当你运行程序时,它会读取变量的值并打印其值。
这是将数值作为参数传递的最明确的方式。
使用%-格式化
让我们使用%-格式化**,** 在print()函数里面把变量作为一个元组来传递。
band = 8
name = "Sarah Fier"
print("The band for %s is %s out of 10" % (name, band))
输出
The band for Sarah Fier is 8 out of 10
以字典的形式传递
你可以把变量作为一个字典传给print()函数。
band = 8
name = "Sarah Fier"
print("The band for %(n)s is %(b)s out of 10" % {'n': name, 'b': band})
输出
The band for Sarah Fier is 8 out of 10
使用新式格式化
在 Python 3.0 中,引入了 format() 方法来更有效地处理复杂的字符串格式化。格式化器的工作原理是将一个或多个替换字段和由一对大括号**{ }** 定义的占位符放入一个字符串中,然后调用 string.format()。
这是一种使用format()方法进行字符串格式化的新风格。它对于重新排序或多次打印同一个是很有用的。
band = 8
name = "Sarah Fier"
print("The band for {} is {} out of 10".format(name, band))
输出
The band for Sarah Fier is 8 out of 10
Python f-string
我们可以在Python 3中使用f-string来打印多个变量。Python f 字符串是对以前格式化方法的一种改进。
它也被称为 "格式化的字符串字面",f-字符串 是字符串字面,它的开头有一个f,大括号中包含将被替换为其值的表达式。
band = 8
name = "Sarah Fier"
print(f"The band for {name} is {band} out of 10")
输出
The band for Sarah Fier is 8 out of 10
本教程就到此为止。
The postHow to Print Multiple Variables in Pythonappeared first onAppDividend.