python - 在 Python 中打印多个参数

这只是我的代码片段:

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

但我希望它打印出来:

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

其中 name 是列表中的变量,score 是整数。如果有帮助的话,这就是 Python 3.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='')
    

    如果您使用的是 Python 2,则无法使用最后两个,因为 print 不是 Python 2 中的函数。但是,您可以从 __future__:

    from __future__ import print_function
    
  2. 在 Python 3.6 中使用新的 f-string 格式:

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

https://stackoverflow.com/questions/15286401/

相关文章:

python - 默认字典的默认字典?

python - 测试 Python 中是否存在可执行文件?

python - '太多的值无法解包',迭代一个字典。键=>字符串,值=>列表

python - 在 Python 3 中从 Web 下载文件

python - 将标准输出重定向到 Python 中的文件?

python - 如何计算 ndarray 中某个项目的出现次数?

python - 如何将 time.struct_time 对象转换为 datetime 对象?

python - 得到一系列列表的笛卡尔积?

python - 在 Python 中将 datetime.date 转换为 UTC 时间戳

python - 为什么 'x' 中的 ('x' 比 'x' == 'x' 快?