在 Python 中打印多个参数 [英] Print multiple arguments in Python
问题描述
这只是我的代码片段:
print("Total score for %s is %s ", name, score)
但我想把它打印出来:
(姓名)的总分是(分数)"
"Total score for (name) is (score)"
其中 name
是列表中的变量,score
是整数.如果有帮助的话,这就是 Python 3.3.
where name
is a variable in a list and score
is an integer. This is Python 3.3 if that helps at all.
推荐答案
有很多方法可以做到这一点.要使用 %
格式修复当前代码,您需要传入一个元组:
There are many ways to do this. To fix your current code using %
-formatting, you need to pass in a tuple:
将其作为元组传递:
Pass it as a tuple:
print("Total score for %s is %s" % (name, score))
具有单个元素的元组看起来像 ('this',)
.
A tuple with a single element looks like ('this',)
.
以下是一些其他常见的做法:
Here are some other common ways of doing it:
将其作为字典传递:
Pass it as a dictionary:
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
还有新样式的字符串格式,可能更容易阅读:
There's also new-style string formatting, which might be a little easier to read:
使用新样式的字符串格式:
Use new-style string formatting:
print("Total score for {} is {}".format(name, score))
使用带有数字的新样式字符串格式(对于重新排序或多次打印相同的数字很有用):
Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):
print("Total score for {0} is {1}".format(name, score))
使用带有显式名称的新式字符串格式:
Use new-style string formatting with explicit names:
print("Total score for {n} is {s}".format(n=name, s=score))
连接字符串:
Concatenate strings:
print("Total score for " + str(name) + " is " + str(score))
我认为最清楚的两个:
只需将值作为参数传递即可:
Just pass the values as parameters:
print("Total score for", name, "is", score)
如果你不希望上面例子中print
自动插入空格,修改sep
参数:
If you don't want spaces to be inserted automatically by print
in the above example, change the sep
parameter:
print("Total score for ", name, " is ", score, sep='')
如果您使用的是 Python 2,将无法使用后两个,因为 print
不是 Python 2 中的函数.但是,您可以从 __未来__
:
If you're using Python 2, won't be able to use the last two because print
isn't a function in Python 2. You can, however, import this behavior from __future__
:
from __future__ import print_function
在 Python 3.6 中使用新的 f
字符串格式:
print(f'Total score for {name} is {score}')
这篇关于在 Python 中打印多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!