[英]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)
由于运算符优先级 ,因此与此相同(请注意额外的括号)
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)
要解决此问题,请在串联中添加括号,以便首先执行它,如下所示:
print ("%s" + "/" + "%s" + "/" + "%s") % (now.month, now.day, now.year)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.