如何在Python中独立替换每个子串实例?求实现方案
解决方案
你可以通过分割字符串+逐个替换拼接的方式实现需求,核心思路是先把原句按目标单词"stupid"拆分,再针对每个拆分位置单独替换并重新拼接句子。
代码实现
sentence = "it is a stupid book and a stupid hat and a stupid computer" # 按"stupid"拆分原句 split_segments = sentence.split("stupid") output_sentences = [] # 遍历每个需要替换的位置(拆分后的段数-1就是目标单词的数量) for i in range(len(split_segments) - 1): # 拼接:前i+1段 + "silly" + 剩余段用"stupid"连接 replaced_parts = split_segments[:i+1] + ["silly"] + split_segments[i+1:] output_sentences.append("".join(replaced_parts)) # 打印结果 for s in output_sentences: print(f'"{s}"')
执行结果
运行后会输出你预期的三个句子:
- "it is a silly book and a stupid hat and a stupid computer"
- "it is a stupid book and a silly hat and a stupid computer"
- "it is a stupid book and a stupid hat and a silly computer"
思路说明
- 用
split("stupid")把原句拆分为["it is a ", " book and a ", " hat and a ", " computer"],拆分后的段数比"stupid"的数量多1; - 循环遍历每个"stupid"的位置(共3次循环),每次只把当前位置的"stupid"替换成"silly",其他位置仍用原单词拼接;
- 最后用
join()把所有段重新组合成完整句子。
这种方法简单直观,不需要依赖复杂的正则,也能精准控制每一次的替换位置。
内容的提问来源于stack exchange,提问作者HosseinSedghian
相关产品推荐
相关产品推荐

