3

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.

2
  • name, age, color = "John", "30", "Red" can fit into f-string using f"Hello, my name is {name} and I'm {age} years old, my favorite colour is {color}" Commented Oct 9, 2019 at 10:26
  • @pissall I want to be able to first define my template string, to have values inserted later; it doesn't seem like this is possible. Commented Oct 9, 2019 at 10:27

1 Answer 1

5

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"))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Is it considered better practice to use f-strings over str.format(), or is it more a matter of preference/convenience?
Matter of preference. When possible to use, I find f-strings easier to read since you don't have to visually scan the expression back and forth to see what the actual value is.
Thanks for the clarification. I guess I could increase readability by using {name} rather than {0}.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.