Search code examples
pythonpython-3.xf-string

Using f-strings as templates


Previously, I've used str.format() as a templating method, for example:

template = "Hello, my name is {0} and I'm {1} years old, my favourite colour is {2}"

# Rest of the program...

print(template.format("John", "30", "Red"))

I've recently learned of f-strings, and I'm interested to see if there's a way of using it in this manner; defining a template and substituting in the appropriate values when needed, rather than the contents of the braces being immediately evaluated.


Solution

  • No, you can't store a f-string for deferred evaluation.

    You could wrap it in a function, but that's not really any more readable imo:

    def template(*, name, age, colour):
        return f"Hello, my name is {name} and I'm {age} years old, my favourite colour is {colour}"
    # ...
    print(template(name="John", age="30", colour="Red"))