在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:
The docs假设新代码首选
format
方法。不过,目前没有删除%格式的计划。在Python2.6中引入了
.format
如果您需要与早期的Python向后兼容,那么应该使用
%
对于Python3和更新版本,应该使用
.format
来确定.format
比%
更强大。将%
移植到.format
很容易,但另一种方法可能并不简单使用
format
方法,特别是当您关心Python 3和未来时。来自the documentation:相关问题 更多 >
编程相关推荐