首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Python中打印多个参数

在Python中打印多个参数
EN

Stack Overflow用户
提问于 2013-03-08 11:51:49
回答 13查看 1.1M关注 0票数 356

这只是我代码的一小段:

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

但我想把它打印出来:

“(姓名)的总分是(分数)”

其中name是列表中的变量,score是整数。这是Python 3.3,如果它有帮助的话。

EN

回答 13

Stack Overflow用户

发布于 2013-03-08 11:52:58

有很多方法可以做到这一点。要使用%-formatting修复当前代码,您需要传入一个元组:

  1. 将其作为元组传递:

print(“%s的总分是%s”%(,score ))print

只有一个元素的元组看起来像('this',)

下面是其他一些常见的方法:

  1. 将其作为字典传递:

print(“%(n)s的总分是%(s)s”% {'n':name,'s':score})

还有新样式的字符串格式化,它可能更容易阅读:

  1. 使用新型字符串格式:

print(“{}的总分是{}”.format(姓名,分数))

  • 使用带数字的新型字符串格式(适用于重新排序或多次打印相同的字符串):

print(“{0}的总分是{1}".format(name,score ))

  • 使用带有显式名称的新型字符串格式:

s=score))

  • Concatenate (“{n}的总分是{s}".format(n=name,print字符串:

print(“+str(名称)+”is“+str(分数))的总分

在我看来,最清楚的两个是:

  1. 只需将值作为参数传递即可:

print(“总分数”,名称,"is",分数)

如果您不希望在上面的示例中由print自动插入空格,请更改sep参数:

print(“总分数",名称,”是",分数,9月=‘’)

如果您使用的是Python2,将无法使用后两个,因为print不是Python2中的函数。但是,您可以从__future__导入此行为:

从Python3.6中导入print_function

  • Use新的f-string格式:

打印(f‘{}的总分是{ score }')

票数 641
EN

Stack Overflow用户

发布于 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}')
票数 63
EN

Stack Overflow用户

发布于 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}') 
票数 52
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15286401

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档