【问题标题】:Why am I getting this python concatenation error?为什么我会收到此 python 连接错误?
【发布时间】:2015-12-15 21:08:20
【问题描述】:

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

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

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)

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

【问题讨论】:

  • 因为它试图将所有值格式化为最后一个 "%s"。您需要将字符串构建在括号中。
  • 这是一个简单的运算符优先级问题

标签: python string-concatenation


【解决方案1】:

因为:

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

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

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

【讨论】:

  • 我没有关注。是不是加法的优势,加法的优先级更高?这不应该也抛弃print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year) ,因为假设它们被连接起来了吗?觉得你可以多解释一下吗?
  • 转念一想,我现在明白了。空格实际上并没有将这些字符串连接在一起,它只是将这些字符串彼此相邻打印。加号和百分号一样充当运算符,混淆了它们的顺序。
【解决方案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)

【讨论】:

  • 我拿了这个是因为解释更彻底,虽然第一个答案帮助我理解了它,尽管我自己花了一段时间看它。当我有加 1 的权力时,我会加 1 第一个答案。
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 2016-01-01
  • 1970-01-01
相关资源
最近更新 更多