python - 艰难地学习 Python : Ex16 Extra Credit

标签 python

当涉及到额外学分的第三个问题时,我感到很困惑。有问题的代码是这样的:

target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

该问题要求您“使用字符串、格式和转义符仅通过一个 target.write() 命令而不是 6 个来打印出第 1 行、第 2 行和第 3 行。”

所以,我想我应该这样写:

target.write("%s + \n + %s + \n + %s + \n") % (line1, line2, line3)

它返回:TypeError: %: 'NoneType' 和 'tuple' 不支持的操作数类型。我对它们做了一些研究,并没有真正找到任何东西,但它使用 %r 返回了同样的错误。

认为 + 号是不正确的,因为它都是一个字符串,所以我删除了它们:

target.write("%s \n %s \n %s \n") % (line1, line2, line3)

仍然没有。然后我尝试了:

target.write("%s" + "\n" + "%s" + "\n" + "%s" + "\n") % (line1, line2, line3)

这个至少将错误更改为:TypeError: %: 'NoneType' 和 'str' 不支持的操作数类型。此变体产生了相同的错误:

target.write("%s") % (line1 + line2 + line3)

无论如何,很明显我被困在某个地方了。我认为我的问题集中在我正在使用的 %s/%r 上,但我找不到我认为可行的替代方案,或者我只是错误地编写了 write 语句。

抱歉,如果服用这种药物,我只是想尝试解释一下我的思考过程。感谢您的协助!

最佳答案

这个怎么样?

target.write("%s\n%s\n%s\n" % (line1, line2, line3))

关于python - 艰难地学习 Python : Ex16 Extra Credit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477041/

相关文章:

python - 更改索引集

python - 优化 Python 代码 - 由于 pandas.core.series.Series.__getitem__ 造成的开销

python - 将复杂的 str 更改为 pandas Dataframe 中的 float

python - 读取大文本文件时数据类型错误

python - 使用 Python 登录使用 OAuth 2.0 的网站

python - 调味包

python - 在带 Altair 的条形图上使用颜色似乎可以防止 zero=False 在比例尺上产生预期效果

python - Beautifulsoup 从 html 中提取所有外部资源

java - Java、C++、Python 中的异常模型

python - SQLAlchemy 和多列不区分大小写的查询