为什么会出现这个python连接错误?

2024-03-28 13:29:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做这个教程,我遇到了一个奇怪的错误。我正在打印日期。你知道吗

因此,在编写示例代码之前,您需要:

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)

这是某种连接问题。我不明白的是,当我连接其他字符串时,以及当我不使用所需字符串的连接时,代码会打印出来。你知道吗


Tags: 字符串代码fromimport示例datetime错误教程
2条回答

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

下一行之所以有效是因为它是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)

因为:

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

与此相同,因为operator precedence(注意额外的括号)

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

相关问题 更多 >