我有这样的代码:

score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)

我想打印出Alice的总分是100,但是我得到了%s的总分是%s Alice 100。我怎样才能让所有东西都以正确的顺序和正确的格式打印出来?


请参见:如何在同一行上打印多个内容,一次打印一个?; 我如何把一个变量的值在一个字符串(插值到字符串)?


当前回答

最简单的方法如下

print(f"Total score for {name} is {score}")

只要在前面加个“f”就行了。

其他回答

这就是我所做的:

print("Total score for " + name + " is " + score)

记住在for和is后面加空格。

最简单的方法如下

print(f"Total score for {name} is {score}")

只要在前面加个“f”就行了。

跟着这个

grade = "the biggest idiot"
year = 22
print("I have been {} for {} years.".format(grade, year))

OR

grade = "the biggest idiot"
year = 22
print("I have been %s for %s years." % (grade, year))

忘记所有其他的,否则大脑将无法映射所有的格式。

用途:.format ():

print("Total score for {0} is {1}".format(name, score))

Or:

// Recommended, more readable code

print("Total score for {n} is {s}".format(n=name, s=score))

Or:

print("Total score for" + name + " is " + score)

Or:

print("Total score for %s is %d" % (name, score))

或者:Python 3.6中的f-string格式:

print(f'Total score for {name} is {score}')

可以使用repr并自动添加“”:

print("Total score for" + repr(name) + " is " + repr(score))

# or for advanced: 
print(f'Total score for {name!r} is {score!r}') 

保持简单,我个人喜欢字符串连接:

print("Total score for " + name + " is " + score)

它适用于Python 2.7和3.X。

注意:如果score是int,那么,你应该将它转换为str:

print("Total score for " + name + " is " + str(score))