我有一些代码,例如:
score = 100
name = 'Alice'
print('Total score for %s is %s', name, score)
我想要打印出来Total score for Alice is 100
,但我得到的是Total score for %s is %s Alice 100
。如何才能以正确的顺序和正确的格式打印所有内容?
See also: How can I print multiple things on the same line, one at a time? https://stackoverflow.com/questions/5598181 ; How do I put a variable’s value inside a string (interpolate it into the string)? https://stackoverflow.com/questions/2960772/
有很多方法可以做到这一点。要修复当前的代码,请使用%
-格式化,需要传入一个元组:
-
将其作为元组传递:
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_function
-
使用新的f
-Python 3.6 中的字符串格式:
print(f'Total score for {name} is {score}')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)