在 Python 中打印多个参数

新手上路,请多包涵

这只是我的代码片段:

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

但我希望它打印出来:

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

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

原文由 user1985351 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 447
1 个回答

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

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

  1. 使用带有数字的新型字符串格式(对于重新排序或多次打印相同的字符串很有用):
    print("Total score for {0} is {1}".format(name, score))

  1. 使用具有显式名称的新型字符串格式:
    print("Total score for {n} is {s}".format(n=name, s=score))

  1. 连接字符串:
    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

  1. 在 Python 3.6 中使用新的 f 格式:
    print(f'Total score for {name} is {score}')

原文由 Blender 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题