Using f-strings as templates

Viewed 1400

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.

1 Answers

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

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

template = lambda *, name, age, colour: 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"))
Related