我在做这个教程,我遇到了一个奇怪的错误。我正在打印日期。你知道吗
因此,在编写示例代码之前,您需要:
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)
这是某种连接问题。我不明白的是,当我连接其他字符串时,以及当我不使用所需字符串的连接时,代码会打印出来。你知道吗
您遇到的问题是由运算符优先级引起的。你知道吗
下一行之所以有效是因为它是string literal concatenation,它的优先级高于
%
运算符。你知道吗以下操作不起作用,因为
+
运算符的优先级低于%
运算符。你知道吗要修复它,请在串联中添加括号,以便首先执行它,如下所示:
因为:
与此相同,因为operator precedence(注意额外的括号)
相关问题 更多 >
编程相关推荐