Answers:
有很多方法可以做到这一点。要使用%-formatting 修复当前代码,您需要传入一个元组:
将其作为元组传递:
print("Total score for %s is %s" % (name, score))具有单个元素的元组看起来像('this',)。
这是其他一些常见的实现方法:
将其作为字典传递:
print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})还有一种新型的字符串格式,可能更容易阅读:
使用新型的字符串格式:
print("Total score for {} is {}".format(name, score))使用带有数字的新型字符串格式(可用于重新排序或多次打印相同的字符):
print("Total score for {0} is {1}".format(name, score))使用具有显式名称的新型字符串格式:
print("Total score for {n} is {s}".format(n=name, s=score))连接字符串:
print("Total score for " + str(name) + " is " + str(score))我认为最清楚的两个是:
只需将值作为参数传递:
print("Total score for", name, "is", score)
如果您不希望print在上面的示例中自动插入空格,请更改sep参数:
print("Total score for ", name, " is ", score, sep='')
如果您使用的是Python 2,将不能使用最后两个,因为print这不是Python 2中的函数。不过,您可以从__future__以下方式导入此行为:
from __future__ import print_functionf在Python 3.6中使用新的-string格式:
print(f'Total score for {name} is {score}')print("Total score for", name, "is", score)
.format()可读性比旧版本更高。的也是简单的情况很好。我还建议以字典作为参数学习,并且-很好地从模板生成文本。还有比较老的。但是模板看起来并不干净:。% (tuple)%print('xxx', a, 'yyy', b).format_map()'ssss {key1} xxx {key2}'string_template % dictionary'ssss %(key1)s xxx %(key2)s'
print(f"Total score for {name} is {score}")使用任何显式的函数调用(只要nameand score明显在范围内)。
有很多打印方法。
让我们看另一个例子。
a = 10
b = 20
c = a + b
#Normal string concatenation
print("sum of", a , "and" , b , "is" , c)
#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c))
# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))
#New style string formatting
print("sum of {} and {} is {}".format(a,b,c))
#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))
EDIT :
#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')
print("sum of {0} and {1} is {2}".format(a,b,c)) 过于矫over过正,print("sum of {} and {} is {}".format(a,b,c)) 除非您想更改订单,否则可以忽略。
使用方法.format():
print("Total score for {0} is {1}".format(name, score))
要么:
// Recommended, more readable code
print("Total score for {n} is {s}".format(n=name, s=score))
要么:
print("Total score for" + name + " is " + score)
要么:
`print("Total score for %s is %d" % (name, score))`
print("Total score for "+str(name)"+ is "+str(score))