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

Python如何按索引或从左到右顺序替换字符串中的指定数字子串

问题原因
  • Python内置的str.replace()是全局匹配所有子串替换,不符合你要求的「从左到右按顺序扫描、匹配到子串后跳过该子串长度继续向后处理」的逻辑。同时替换规则需要优先匹配更长的目标串,你原有代码的替换顺序会导致短串先被替换,长串永远无法命中。
  • 原有代码开头的fin.close()属于语法错误,文件还未打开就调用关闭方法会直接抛出运行异常。
实现代码
original_str = "001001001001001001001001001001001001001101100100110110011011001101011010011010110011011"
# 替换规则按匹配串长度倒序排列,优先匹配更长的串
rules = [
    ("11001", "111"),
    ("1101", "11"),
    ("1001", "011"),
    ("101", "01")
]

res = []
idx = 0
str_len = len(original_str)

while idx < str_len:
    is_match = False
    for old_sub, new_sub in rules:
        sub_len = len(old_sub)
        if idx + sub_len <= str_len and original_str[idx:idx+sub_len] == old_sub:
            res.append(new_sub)
            idx += sub_len
            is_match = True
            break
    if not is_match:
        res.append(original_str[idx])
        idx += 1

final_str = "".join(res)
# 写入文件
with open("2x.txt", "w") as f:
    f.write(final_str)

# 校验结果是否符合预期
expected = "00011000110001100011000110001100110110011011010110101100110111011"
print(final_str == expected) # 输出为True即符合要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:54:03