用Python打印多个参数

2024-04-18 14:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这只是我的一段代码:

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

但我想打印出来:

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

其中,name是列表中的变量,score是整数。如果这有帮助的话,这就是Python3.3。


Tags: 代码name列表foris整数totalscore
3条回答

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

  1. 以元组形式传递:

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

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

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

  1. 作为字典传递:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

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

  1. 使用新样式的字符串格式:

    print("Total score for {} is {}".format(name, score))
    
  2. 对数字使用新样式的字符串格式(用于重新排序或多次打印同一个字符串):

    print("Total score for {0} is {1}".format(name, score))
    
  3. 对显式名称使用新样式的字符串格式:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. 连接字符串:

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

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

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

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

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

    print("Total score for ", name, " is ", score, sep='')
    

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

    from __future__ import print_function
    
  2. 在Python 3.6中使用新的f字符串格式:

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

有很多方法可以打印出来。

让我们看一看另一个例子。

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))

或:

// 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))`

相关问题 更多 >