字符串占位符的更python的方式?



是否有更python的方法来完成以下操作?f字符串似乎需要一个已定义的变量(没有空表达式),但如果我想稍后定义@names和@locations,最好的方法是什么?

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)

{}'s从f字符串中转义出来,然后在format中使用它们:

now = 'hey'
s = f'{now}, then {{names}} or {{locations}}'
# later on
print(s.format(names='foo', locations='bar'))

注:如果立即膨胀也含有{},则需要注意。

最新更新