Format a string later?

python, string-formatting

Solution

Sure it is possible. Just store the strings and call `.format()` on them later:

>>> someformat = 'Hello {}!'
>>> someformat
'Hello {}!'
>>> print someformat.format('World')
Hello World!

`.format()` is just a method on a string, only when you call that method will the string be interpreted as a template. Just like `.strip()` and `.join()`, you can call that method on any string object at a time of your choosing.

Problem

If I have a list of strings, some of which contain codes contained within `{}`, is it possible to use `format()` on those strings at a later time? In the case I have I want to write some flavor text for bodily damage such as `"He appears to be limping on his {1} leg."` but I would like to format that string with either 'left' or 'right' depending on the leg in question.

Original source