为什么我会收到此 python 连接错误?

Why am I getting this python concatenation error?

我正在学习本教程,并且 运行 遇到了这个奇怪的错误。我正在打印日期。

所以在示例代码之前,你需要有:

from datetime import datetime
now = datetime.now()

这将打印

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year)

这也会

print "pizza" + "pie"

这也会

print "%s/%s/%s" % (now.month, now.day, now.year)

但是当我介绍连接运算符时:

#Traceback (most recent call last):
#  File "python", line 4, in <module>
#TypeError: not all arguments converted during string formatting
print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

这是某种串联问题。我不明白的是,当我连接其他字符串时以及当我不对我想要的字符串使用连接时,代码将打印出来。

因为这个:

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

与此相同,由于operator precedence(注意多出的括号)

print "%s" + "/" + "%s" + "/" + ("%s" % (now.month, now.day, now.year))

您遇到的问题是由运算符优先级引起的。

以下行有效,因为这是 string literal concatenation,它的优先级高于 % 运算符。

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year)

以下内容不起作用,因为 + 运算符的优先级低于 % 运算符。

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

要修复它,请在连接中添加括号,以便它首先执行,如下所示:

print ("%s" + "/" + "%s" + "/" + "%s") % (now.month, now.day, now.year)