A more pythonic way for string placeholders?

Question:

Is there a more pythonic way to do the following? F-strings seem to require a defined variable (no empty expressions) but if I want to define @names and @locations later on, what is the best way to go about it?

funct_a = call_function()

str_a = f"a very long string of text that contains {funct_a} and also @names or @locations"

... 
large chunk of code that modifies str_a and defines var_a, var_b, var_c, var_d
...

if <conditional>:
    str_b = str_a.replace("@names", var_a).replace("@locations", var_b)
elif <conditional>:
    str_b = str_a.replace("@names", var_c).replace("@locations", var_d)
Asked By: WhimsicalWhale

||

Answers:

Escape {}‘s from the f-string and use them later on in format:

now = 'hey'

s = f'{now}, then {{names}} or {{locations}}'

# later on

print(s.format(names='foo', locations='bar'))

NB: requires some care if the immediate expansion also contains {}.

Answered By: gog
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.