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

Python 3.x 如何将两个配置路径变量合并为含中间参数的单个变量

实现方法

你可以通过两种方式实现需求,无需保留原有的两个变量拼接逻辑:

方案1:直接在配置中定义合并后的模板(推荐)

直接在配置文件新增单个路径变量,按需预留对应数量的占位符即可,你可以选择顺序占位符或者命名占位符:

顺序占位符写法

如果你的最终路径需要替换3个位置(原cfg的占位符、两个路径中间的tmpl_name、原amd的占位符),配置写法如下:

combined_path: /api/config/devices/{}/test/{}/api/bind/templateData/{}/test2

调用代码:

# 按顺序传入对应参数即可,效果和原有拼接逻辑完全一致
result = self.configs["combined_path"].format(devices_param, tmpl_name, tmpl2_name)

如果不需要额外插入中间参数,仅替换原两个配置的占位符,配置写法调整为:

combined_path: /api/config/devices/{}/test/api/bind/templateData/{}/test2

调用时传入两个参数即可。

命名占位符写法(可读性更高,避免参数顺序错误)

配置写法:

combined_path: /api/config/devices/{devices_id}/test/{tmpl_name}/api/bind/templateData/{tmpl2_name}/test2

调用代码:

result = self.configs["combined_path"].format(
    devices_id=你的设备参数,
    tmpl_name=tmpl_name,
    tmpl2_name=tmpl2_name
)

方案2:不修改配置,运行时拼接模板

如果不想改动原有配置项,也可以在代码中先拼接两个模板字符串,再统一传参:

# 如需在两个路径中间插入参数,拼接时新增对应占位符即可
combined_template = self.configs["cfg"] + "/{}" + self.configs["amd"]
# 按顺序传入对应数量的参数完成替换
result = combined_template.format(devices_param, tmpl_name, tmpl2_name)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 17:33:00