我不明白 format() 和 ... (python) 之间有什么区别 [英] I don't get what's the difference between format() and ... (python)

查看:27
本文介绍了我不明白 format() 和 ... (python) 之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里的新手很困惑.使用有什么区别:

Confused newbie here. What's the difference between using:

print ("So you are {0} years old".format(age))

print ("So you are", age, "years old")

两者都有效.

推荐答案

实际上有很大的不同.前者使用字符串的format 方法来创建一个字符串.后者,将几个参数传递给 print 函数,它将把它们全部连接起来,在它们之间添加一个空格(默认).

Actually there's a huge difference. The former use string's format method to create a string. The latter, pass several arguments to print function, which will concatenate them all adding a whitespace (default) between them.

前者要强大得多,例如,您可以使用格式语法 完成以下操作:

The former is far more powerful, for instance, you can use the format syntax to accomplish things like:

# trunc a float to two decimal places
>>> '{:.2f}'.format(3.4567)
'3.46'

# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'

它类似于早期版本的python中使用的printf样式格式,带有%操作符:(即:"%d"%3) 现在 str.format() 被推荐用于 % 运算符,并且是 Python 3 中的新标准.

It is similar to printf style formats used in earlier versions of python with the % operator: (ie: "%d" % 3) Now str.format() is recommended over the % operator and is the new standard in Python 3.

这篇关于我不明白 format() 和 ... (python) 之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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