【问题标题】:TypeError : not all arguments converted during string formattingTypeError : 在字符串格式化期间并非所有参数都转换了
【发布时间】:2021-08-19 18:01:56
【问题描述】:
print("The mangy, scrawny stray dog %s gobbled down" +
"the grain-free, organic dog food." %'hurriedly')

上面的语句给了我错误“TypeError : not all arguments convert during string formatting”。

任何帮助将不胜感激。

【问题讨论】:

  • 删除字符串文字之间的++ 的优先级低于 %,并且相邻的字符串文字无论如何都会连接起来。

标签: python python-3.x string printing typeerror


【解决方案1】:

+ 的优先级低于%,因此对于您的代码,Python 会尝试评估 "the grain-free, organic dog food." %'hurriedly',这没有意义,因为该格式字符串不包含 %s 部分。

删除字符串文字之间的+

print("The mangy, scrawny stray dog %s gobbled down "
      "the grain-free, organic dog food." %'hurriedly')

无论如何,相邻的字符串文字都会被连接,因此您不需要+

或者,如果您使用的是 Python 3.6 或更高版本,请使用 f-string:

adverb = 'hurriedly'
print(f"The mangy, scrawny stray dog {adverb} gobbled down "
      "the grain-free, organic dog food.")

【讨论】:

    猜你喜欢
    • 2015-01-21
    • 2015-03-30
    • 1970-01-01
    • 2022-01-10
    • 2018-06-14
    • 2020-08-23
    • 2015-10-28
    相关资源
    最近更新 更多