【问题标题】:Python - what is the difference between these 3 methods of printing variables?Python - 这三种打印变量的方法有什么区别?
【发布时间】:2016-07-12 10:07:00
【问题描述】:

我正在尝试教我的朋友 Python,并向他展示了 3 种打印不同类型变量的方法,而无需先将它们转换为字符串,但他想知道应该使用哪个,我不知道好久没用Python了,希望大家帮帮忙:

print("There are %d people in total" % num_people)

print("There are", num_people, "people in total")

print("There are {} people in total".format(num_people))

我知道 format 方法可以执行其他更强大的字符串操作操作,但除此之外,我不确定哪种方法是首选方法。我不知道为什么第一种方法存在,因为第二种方法似乎更简单。

对此有什么想法吗?谢谢!

【问题讨论】:

    标签: python string variables printing


    【解决方案1】:

    Python 风格指南建议使用format 方法。这是该文档的链接:"PEP 3101"

    【讨论】:

      【解决方案2】:

      关于%.format,请参阅this 等类似问题,正如其他人所指出的那样。

      关于

      print("There are", num_people, "people in total")
      

      这实际上只是print() 函数提供的便利。签名不是只打印一个参数,而是允许多个参数,它们分别转换为字符串,然后用一个空白(默认情况下)作为分隔符连接。这对于快速输出多个对象非常有用,但通常不适合生成格式化输出。仅打印一个高精度给出的十进制数可能会产生有限可用性的输出。有关其功能的更多信息,请参阅the documentation of print()

      【讨论】:

      • 谢谢,我主要关心的是使用多个参数打印和格式化之间的区别,所以这很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2013-09-08
      • 2019-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多