我没有得到format()和...(python)之间的区别

use*_*794 3 python string variables python-3.x

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

print ("So you are {0} years old".format(age))
Run Code Online (Sandbox Code Playgroud)

print ("So you are", age, "years old")
Run Code Online (Sandbox Code Playgroud)

两者都有效.

Pau*_* Bu 7

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

前者功能更强大,例如,您可以使用格式语法来完成以下操作:

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

# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'
Run Code Online (Sandbox Code Playgroud)

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