Python的打印方式:用“格式”还是百分比形式? [英] Python way of printing: with 'format' or percent form?

查看:147
本文介绍了Python的打印方式:用“格式”还是百分比形式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  user =Alex
编号= 38746
print(%s问%2 $ stackoverflow.com上的问题%(用户,编号))
print({0}问stackoverflow.com上的{1} (用户,号码))

是否有一种方法比另一种更受欢迎?他们是否相同,有什么区别?什么形式应该使用,特别是对于Python3?

解决方案

使用格式方法,特别是如果你关心Python 3和未来。从文档: / b>


此处描述的格式化操作[%substitutions]已过时,可能会在未来版本的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))

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?

解决方案

Use the format method, especially if you're concerned about Python 3 and the future. From the documentation:

The formatting operations described here [% substitutions] are obsolete and may go away in future versions of Python. Use the new String Formatting in new code.

这篇关于Python的打印方式:用“格式”还是百分比形式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆