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

Python实现:字符串指定内容与列表元素拼接替换并遍历

解决方案

直接用字符串替换结合for循环就能搞定,注意别用list当变量名(这是Python内置类型,会引发冲突),代码示例:

base_str = "the secret key is A"
items = ["123", "234", "345"]

for item in items:
    # 把原字符串里的"A"替换成"A"+当前列表元素
    new_str = base_str.replace("A", f"A{item}")
    print(new_str)

补充说明

  • 用f-string可以快速完成字符串拼接,f"A{item}"会自动把item的值拼在"A"后面,写法简洁直观。
  • 如果原字符串里有多个"A",只想替换最后一个,可以改用切片拼接的方式:
    new_str = base_str[:-1] + f"A{item}"
    

运行代码后,就能得到你期望的结果:

the secret key is A123
the secret key is A234
the secret key is A345

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:25:18