Python打印方式:使用“format”或percent form?

2024-05-17 03:43:52 发布

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

在Python中,生成格式化输出的方式似乎有两种:

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?


Tags: 方法comformatnumberon方式stackoverflow形式
3条回答

The docs假设新代码首选format方法。不过,目前没有删除%格式的计划。

在Python2.6中引入了.format

如果您需要与早期的Python向后兼容,那么应该使用%

对于Python3和更新版本,应该使用.format来确定

.format%更强大。将%移植到.format很容易,但另一种方法可能并不简单

使用format方法,特别是当您关心Python 3和未来时。来自the documentation

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 deprecate printf-style formatting.

相关问题 更多 >