You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何格式化其他文件中字典内的f-string?

解决方案

你可以通过以下几种优雅的方式,在不移动字典的前提下完成跨文件的字符串格式化:

方法1:使用str.format()替换f-string

把templates.py中的f-string改成带命名占位符的普通字符串,之后在app.py中批量调用format()方法填充变量:

templates.py

dict1 = {
    "greeting": "Hello, {name}!",
    "info": "You are {age} years old and from {city}"
}

app.py

from templates import dict1

# 你的本地变量
name = "Alice"
age = 30
city = "New York"

# 批量格式化字典中的所有字符串
formatted_dict = {
    key: value.format(name=name, age=age, city=city)
    for key, value in dict1.items()
}

这种方式无需额外依赖,语法直观,适合变量数量固定的场景。

方法2:使用string.Template类

如果需要更安全的格式化(比如避免格式字符串注入风险),可以用Python标准库的string.Template:

templates.py

from string import Template

dict1 = {
    "greeting": Template("Hello, $name!"),
    "info": Template("You are $age years old and from $city")
}

app.py

from templates import dict1

# 把变量打包成上下文字典
context = {"name": "Alice", "age": 30, "city": "New York"}

# 批量替换占位符
formatted_dict = {
    key: template.substitute(context)
    for key, template in dict1.items()
}

Template的占位符语法($变量名)和f-string区分开,适合需要动态处理外部输入的场景。

方法3:将字典封装为函数

如果想保留f-string的简洁语法,可以把templates.py中的字典包装成一个接收参数的函数,在app.py中调用时传入变量:

templates.py

def get_formatted_content(name, age, city):
    return {
        "greeting": f"Hello, {name}!",
        "info": f"You are {age} years old and from {city}"
    }

app.py

from templates import get_formatted_content

# 你的本地变量
name = "Alice"
age = 30
city = "New York"

# 调用函数获取格式化后的字典
formatted_dict = get_formatted_content(name, age, city)

这种方式把格式化逻辑完全封装在templates.py中,app.py只需要关注传参,代码耦合度更低。

内容的提问来源于stack exchange,提问作者gagilein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 17:05:21