这只是我代码的一小段:
print("Total score for %s is %s ", name, score)
但我想把它打印出来:
“(姓名)的总分是(分数)”
其中name
是列表中的变量,score
是整数。这是Python 3.3,如果它有帮助的话。
发布于 2013-03-08 11:52:58
有很多方法可以做到这一点。要使用%
-formatting修复当前代码,您需要传入一个元组:
print(“%s的总分是%s”%(,score ))print
只有一个元素的元组看起来像('this',)
。
下面是其他一些常见的方法:
print(“%(n)s的总分是%(s)s”% {'n':name,'s':score})
还有新样式的字符串格式化,它可能更容易阅读:
print(“{}的总分是{}”.format(姓名,分数))
print(“{0}的总分是{1}".format(name,score ))
s=score))
print(“+str(名称)+”is“+str(分数))的总分
在我看来,最清楚的两个是:
print(“总分数”,名称,"is",分数)
如果您不希望在上面的示例中由print
自动插入空格,请更改sep
参数:
print(“总分数",名称,”是",分数,9月=‘’)
如果您使用的是Python2,将无法使用后两个,因为print
不是Python2中的函数。但是,您可以从__future__
导入此行为:
从Python3.6中导入print_function
f
-string格式:打印(f‘{}的总分是{ score }')
发布于 2016-08-11 21:07:39
有很多方法可以打印出来。
让我们用另一个例子来看看。
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}')
发布于 2018-01-18 19:23:38
用法:.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))
或者:从Python3.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}')
https://stackoverflow.com/questions/15286401
复制相似问题