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

如何在Python中编程替换数组字符串为实际值而非硬编码

在Python中批量替换字符串中的数组占位符

下面提供几种无需硬编码的实现方式,满足你的需求:

方法一:使用str.format()(简洁高效)

先将数据存入列表,调整字符串占位符为位置索引格式,通过format()批量注入值,同时可直接给替换内容添加加粗格式:

test = ["david", "23", "thank you"]
# 占位符{0}、{1}对应列表索引
my_string = "Hi, my name is **{0}** and I am **{1}** years old"
result = my_string.format(*test)
print(result)

输出:

Hi, my name is david and I am 23 years old

方法二:正则表达式动态匹配原占位符

如果不想修改原字符串的test[0]格式,用正则匹配占位符并动态替换:

import re

test = ["david", "23", "thank you"]
my_string = "Hi, my name is test[0] and I am test[1] years old"

# 定义匹配替换逻辑
def replace_match(match):
    # 提取括号内的索引数字
    idx = int(match.group(1))
    return f"**{test[idx]}**"

# 匹配test[数字]格式的占位符并替换
result = re.sub(r'test\[(\d+)\]', replace_match, my_string)
print(result)

输出:

Hi, my name is david and I am 23 years old

方法三:使用string.Template模板替换

适合需要更清晰占位符命名的场景,调整占位符格式后通过模板注入值:

from string import Template

test = ["david", "23", "thank you"]
# 自定义占位符格式
my_template = Template("Hi, my name is **$name** and I am **$age** years old")
result = my_template.substitute(name=test[0], age=test[1])
print(result)

输出同样符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:01:20