There are many ways to do this.
(有很多方法可以做到这一点。)
To fix your current code using %
-formatting, you need to pass in a tuple: (要使用%
-formatting修复当前代码,您需要传入一个元组:)
Pass it as a tuple:
(将其作为元组传递:)
print("Total score for %s is %s" % (name, score))
A tuple with a single element looks like ('this',)
.
(具有单个元素的元组看起来像('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))
The clearest two, in my opinion:
(我认为最清楚的两个是:)
Just pass the values as parameters:
(只需将值作为参数传递:)
print("Total score for", name, "is", score)
If you don't want spaces to be inserted automatically by print
in the above example, change the sep
parameter:
(如果您不希望在上面的示例中通过print
自动插入空格,请更改sep
参数:)
print("Total score for ", name, " is ", score, sep='')
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__
:
(如果您使用的是Python 2,将无法使用最后两个,因为print
在Python 2中不是函数。但是,您可以从__future__
导入此行为:)
from __future__ import print_function
Use the new f
-string formatting in Python 3.6:
(在Python 3.6中使用新的f
-string格式:)
print(f'Total score for {name} is {score}')
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…