动态加载f字符串格式

Set*_*top 3 python f-string

我想构建一个工具,将 fstring 格式存储在配置文件中。

config = load_config()

def build_fstring(str):
  return ...   # <-- issue is there

chosen_format = config.get("chosen_format")  # returns '{k},{v}'

fstring = build_fstring(chosen_format) # may return something like 'f"{k},{v}"'

for (k,v) in d.items():
  print(fstring)  # fstring is evaluated here

Run Code Online (Sandbox Code Playgroud)

我的问题是 fstring 是在变量已知之前编译的。

有办法做到吗?

blh*_*ing 6

根据PEP-498,f 字符串旨在“提供一种在字符串文字中嵌入表达式的方法”,这意味着 f 字符串首先是字符串文字,并且尝试将变量的值计算为 f -string 违背了它的目的。

为了使用变量作为字符串格式化模板,使用该str.format方法会更容易:

k, v = 1, 2
chosen_format = '{k},{v}'
print(chosen_format.format(**locals()))
Run Code Online (Sandbox Code Playgroud)

这输出:

1,2
Run Code Online (Sandbox Code Playgroud)