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

如何在Python中查找并替换特定字符包裹的字符串内容?

修正方案及原代码问题分析

原代码问题

你当前的代码中,两次调用the_long_string.index('$$')都会返回第一个$$的起始位置,导致切片的起始索引(index('$$')+2)大于结束索引(index('$$')),最终得到空字符串,自然没有输出。

高效解决方案

方法1:正则表达式(推荐,适配复杂场景)

使用Python的re.sub函数,通过正则匹配所有被$$包裹的子串,统一替换为目标值:

import re

the_long_string = "$$firstOccurance$$ some other words here then $$secondOccurance$$"
replacement_value = "someNewString"
# 正则匹配所有$$包裹的内容,非贪婪模式避免跨匹配
result = re.sub(r'\$\$(.*?)\$\$', replacement_value, the_long_string)
print(result)

输出结果:

someNewString some other words here then someNewString
  • 正则说明:\$\$匹配字面量$$,(.*?)采用非贪婪匹配,确保每次只匹配一对$$之间的内容,不会把多个$$包裹的区域合并成一个。

方法2:字符串拆分拼接(无需导入模块)

利用split和join实现替换,适合简单场景:

the_long_string = "$$firstOccurance$$ some other words here then $$secondOccurance$$"
replacement_value = "someNewString"
# 按$$拆分字符串,得到的列表中,非包裹内容位于偶数索引位
parts = the_long_string.split('$$')
# 用替换值连接所有偶数索引的元素,等价于替换所有$$包裹区域
result = replacement_value.join(parts[::2])
print(result)

输出结果与方法1一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:05:42