2

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.

clubby789
  • 2,543
  • 4
  • 16
  • 32
  • `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}"` – pissall Oct 09 '19 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. – clubby789 Oct 09 '19 at 10:27

1 Answers1

5

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"))
AKX
  • 152,115
  • 15
  • 115
  • 172
  • 1
    Thanks. Is it considered better practice to use f-strings over `str.format()`, or is it more a matter of preference/convenience? – clubby789 Oct 09 '19 at 10:24
  • 2
    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. – AKX Oct 09 '19 at 10:25
  • Thanks for the clarification. I guess I could increase readability by using `{name}` rather than `{0}`. – clubby789 Oct 09 '19 at 10:27