gpt4 book ai didi

Python打印方式: with 'format' or percent form?

转载 作者:IT老高 更新时间:2023-10-28 21:08:50 27 4
gpt4 key购买 nike

在 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?

最佳答案

使用 format 方法,特别是如果您担心 Python 3 和 future 。来自 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.

关于Python打印方式: with 'format' or percent form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12382719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com