小编Set*_*top的帖子

动态加载f字符串格式

我想构建一个工具,将 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 是在变量已知之前编译的。

有办法做到吗?

python f-string

3
推荐指数
1
解决办法
611
查看次数

标签 统计

f-string ×1

python ×1