Python 打印方式:使用“格式"还是百分比形式? [英] Python way of printing: with 'format' or percent form?
问题描述
在 Python 中似乎有两种不同的生成格式化输出的方法:
In Python there seem to be two different ways of generating formatted output:
user = "Alex"
number = 38746
print("%s asked %d questions on stackoverflow.com" % (user, number))
print("{0} asked {1} questions on stackoverflow.com".format(user, number))
有没有一种方式比另一种方式更受欢迎?它们是等价的,有什么区别?应该用什么形式,尤其是Python3?
Is there one way to be preferred over the other? Are they equivalent, what is the difference? What form should be used, especially for Python3?
推荐答案
使用 format
方法,尤其是当您关心 Python 3 和未来时.来自文档:
Use the format
method, especially if you're concerned about Python 3 and the future. From the documentation:
此处描述的格式化操作以 C 的 printf()
为模型句法.它们只支持某些内置类型的格式.这使用二元运算符意味着可能需要小心才能正确格式化元组和字典.作为新:ref:string-formatting
语法更灵活,可以处理元组和字典自然,建议用于新代码.然而,有目前没有计划弃用 printf
样式的格式.
The formatting operations described here are modelled on C's
printf()
syntax. They only support formatting of certain builtin types. The use of a binary operator means that care may be needed in order to format tuples and dictionaries correctly. As the new :ref:string-formatting
syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecateprintf
-style formatting.
这篇关于Python 打印方式:使用“格式"还是百分比形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!