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

Python读取文件后调用replace方法未生效的问题排查

问题解决:Python字符串replace未生效的原因及修复

Python中的字符串是不可变对象,str.replace()方法不会直接修改原字符串,而是返回一个完成替换操作的新字符串。你的代码里仅调用了content.replace("Here",""),但没有将返回的新字符串重新赋值给content变量,所以原字符串完全没变化,导致输出看起来替换未生效。

修复后的脚本如下:

with open(r'test.txt',"r") as text_file:
    content = text_file.read()
    print("the content:")
    print(content)
    
    # 将replace返回的新字符串赋值给content
    content = content.replace("Here","")
    print("The replaced content:")
    print(content)

如果需要把修改后的内容写回原文件,可以添加写入步骤:

with open(r'test.txt',"r") as text_file:
    content = text_file.read()
    content = content.replace("Here","")

# 写入修改后的内容
with open(r'test.txt',"w") as text_file:
    text_file.write(content)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 17:47:02