如何格式化其他文件中字典内的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
相关产品推荐
相关产品推荐

