我有这样的代码:
score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)
我想打印出Alice的总分是100,但是我得到了%s的总分是%s Alice 100。我怎样才能让所有东西都以正确的顺序和正确的格式打印出来?
请参见:如何在同一行上打印多个内容,一次打印一个?; 我如何把一个变量的值在一个字符串(插值到字符串)?
我有这样的代码:
score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)
我想打印出Alice的总分是100,但是我得到了%s的总分是%s Alice 100。我怎样才能让所有东西都以正确的顺序和正确的格式打印出来?
请参见:如何在同一行上打印多个内容,一次打印一个?; 我如何把一个变量的值在一个字符串(插值到字符串)?
当前回答
保持简单,我个人喜欢字符串连接:
print("Total score for " + name + " is " + score)
它适用于Python 2.7和3.X。
注意:如果score是int,那么,你应该将它转换为str:
print("Total score for " + name + " is " + str(score))
其他回答
试试:
print("Total score for", name, "is", score)
使用f-string:
print(f'Total score for {name} is {score}')
Or
使用.format:
print("Total score for {} is {}".format(name, score))
print("Total score for %s is %s " % (name, score))
%s可以替换为%d或%f
有很多种打印方法。
让我们看另一个例子。
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}')
用途:.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}')