这里是困惑的新手。使用有什么区别:
print ("So you are {0} years old".format(age))
AND
print ("So you are", age, "years old")
两者都有效。
其实差别很大。前者使用字符串format https://docs.python.org/3/library/stdtypes.html?highlight=str#str.format创建字符串的方法。后者,将几个参数传递给print https://docs.python.org/3.4/library/functions.html?#print函数,它将把它们全部连接起来,在它们之间添加一个空格(默认)。
前者更强大,例如,您可以使用格式语法 https://docs.python.org/3/library/string.html#formatstrings完成以下任务:
# trunc a float to two decimal places
>>> '{:.2f}'.format(3.4567)
'3.46'
# access an objects method
>>> import math
>>> '{.pi}'.format(math)
'3.141592653589793'
它类似于printf
早期版本的 python 中使用的样式格式%
运算符:(即:"%d" % 3
) Now str.format()
推荐超过%
运算符 and 是 Python 3 中的新标准。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)