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

Python 2字典字符串格式化转Python3 .format()的正确方法

用.format()替代Python 2字典字符串格式化的正确方式

你之前的写法问题在于直接把字典作为单个参数传给format(),导致整个字典被当成值填充到占位符里。要对应Python 2中%(key)s的字典格式化逻辑,有两种正确的写法:

方法1:使用关键字参数解包字典

保持格式化字符串里的占位符对应字典的键,然后用**操作符解包字典传入format():

string = "Today I saw a {animal} at the park."
ex_dict = {"animal": "dog"}
mod_string = string.format(**ex_dict)
print(mod_string)

运行结果:

Today I saw a dog at the park.

方法2:直接在占位符中指定字典键的访问

如果不想解包字典,可以在占位符里明确指定字典的键访问方式,直接传入字典作为参数:

string = "Today I saw a {0[animal]} at the park."
ex_dict = {"animal": "dog"}
mod_string = string.format(ex_dict)
print(mod_string)

或者给字典参数命名,让占位符更清晰:

string = "Today I saw a {data[animal]} at the park."
ex_dict = {"animal": "dog"}
mod_string = string.format(data=ex_dict)
print(mod_string)

这两种写法的运行结果同样符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 20:05:33