Search code examples
pythontupleswrappertext-based

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:

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.


Solution

  • In order to use variables in a string you have to use a format or f string.

    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...