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