简体   繁体   English

如何使 textwrap 与一些文本一起打印一个变量?

[英]How do I make textwrap print a variable along with some text?

This is the code I'm using to make part of a text-based game:这是我用来制作基于文本的游戏的一部分的代码:

armour = int(0)
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."
wrapper = textwrap.TextWrapper(width=90)
words = wrapper.wrap(text=message)
for element in words:
  print(element) 

I want to use textwrap to print the text without the words getting split at the end of a line, which works fine, but when I put a variable (armour) in the text it comes up with an error message:我想使用 textwrap 打印文本而不会在行尾拆分单词,这很好,但是当我在文本中放置一个变量(盔甲)时,它会出现一条错误消息:

Traceback (most recent call last):
  File "main.py", line 126, in <module>
    intro()
  File "main.py", line 20, in intro
    left()
  File "main.py", line 47, in left
    fight()
  File "main.py", line 112, in fight
    words = wrapper.wrap(text=message)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/textwrap.py", 
line 351, in wrap
    chunks = self._split_chunks(text)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/textwrap.py", 
line 337, in _split_chunks
    text = self._munge_whitespace(text)
  File "/nix/store/p21fdyxqb3yqflpim7g8s1mymgpnqiv7-python3-3.8.12/lib/python3.8/textwrap.py", 
line 154, in _munge_whitespace
    text = text.expandtabs(self.tabsize)
AttributeError: 'tuple' object has no attribute 'expandtabs'

Does anyone know how to fix this?有谁知道如何解决这一问题? I don't want to use \n instead of textwrap due to different monitor sizes.由于显示器尺寸不同,我不想使用 \n 而不是 textwrap 。

In order to use variables in a string you have to use a format or f string.为了在字符串中使用变量,您必须使用formatf字符串。

count = 20
#string formatting versions
newest  = f'I have {count} apples left.'
older   = 'I have {} apples left.'.format(count)
ancient = 'I have %i apples left.' % count

more...更多的...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM