为什么这样操作不能替换字符串中字符呢?

在导入文本的with结构下对导入的文档进行输出时,为什么这样不能将python变为C++呢?


with open('learning_python.txt') as file:
    for line in file:
        line.replace('python','C++')
        print(line.rstrip())

line = line.replace('python','C++')

line.replace() 是返回一个新的字符串,不是直接修改原字符串对象。
要把替换后返回的新字符串重新赋值给 line

    line=line.replace('python','C++')
with open('learning_python.txt') as file:
    for line in file:
        line=line.replace('python','C++')
        print(line.rstrip())