0

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)
  • 2
    Consider using the `str.format` method or the `string.Template` class. – chepner Nov 17 '22 at 16:42
  • Does this answer your question? [How to postpone/defer the evaluation of f-strings?](https://stackoverflow.com/questions/42497625/how-to-postpone-defer-the-evaluation-of-f-strings) – Bernardo Duarte Nov 17 '22 at 16:46

1 Answers1

5

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 {}.

gog
  • 10,367
  • 2
  • 24
  • 38