【问题标题】:dynamically load f-string format动态加载 f-string 格式
【发布时间】:2022-07-26 17:31:40
【问题描述】:

我想构建一个将 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

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

有办法吗?

【问题讨论】:

    标签: python f-string


    【解决方案1】:

    我发现了一个使用eval的技巧:

    config = load_config()
    
    chosen_format = config.get("chosen_format")  # returns '{k},{v}'
    
    for (k,v) in d.items():
      print(eval('f"'+chosen_format+'"'))
    
    

    但我对代码的简洁性不太满意——print 不应该知道如何构建内容——以及评估每条记录的代码的性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-02
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      相关资源
      最近更新 更多