You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何使用textwrap打印含变量的文本并解决报错

问题根因

报错是因为你传入wrapper.wrap()的message不是预期的字符串类型,而是元组。
Python中直接用逗号分隔多个值,会自动将这些值打包为元组——你定义message时用逗号分隔字符串片段和str(armour),最终得到的是一个包含3个元素的元组,而非拼接完成的完整字符串。textwrap模块的内部逻辑会对传入的文本调用字符串专属的expandtabs()方法,元组没有这个方法,自然会抛出属性错误。
另外你原始代码中直接在双引号包裹的字符串内部换行,本身也不符合Python语法,会在运行前就触发语法错误。

修复方法

将message正确构造为单个完整字符串即可,最推荐使用可读性最好的f-string语法(Python 3.6+版本支持),修复后的完整可运行代码如下:

import textwrap

armour = 0
# 外层括号包裹字符串,代码编辑时折行不会影响实际字符串内容,方便维护
message = (
    f"You have no weapons to fight with. The bokoblin hits you with its club (3 damage) "
    f"but your armour reduces the damage (-{armour}) and you manage to escape."
)
wrapper = textwrap.TextWrapper(width=90)
words = wrapper.wrap(text=message)
for line in words:
    print(line)

如果你使用3.6以下的Python版本,可以选择以下任意一种字符串构造方式替换message定义:

  • 使用str.format()方法拼接:
message = (
    "You have no weapons to fight with. The bokoblin hits you with its club (3 damage) "
    "but your armour reduces the damage (-{}) and you manage to escape.".format(armour)
)
  • 使用+手动拼接(注意所有参与拼接的内容都必须是字符串类型):
message = "You have no weapons to fight with. The bokoblin hits you with its club (3 damage) but your armour reduces the damage (-" + str(armour) + ") and you manage to escape."

修复后textwrap会正常处理完整文本,按照设定的宽度自动换行且不会拆分行尾单词,你可以根据不同显示器的显示区域尺寸动态调整width参数,无需手动插入\n换行符。

内容的提问来源于stack exchange,提问作者CretaceousCat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 01:45:36