replace 方法不会修改原始字符串,而是返回一个新的字符串,其中进行了替换。
with open('data.txt') as f:
content = f.readlines()
New = []
for line in content:
if 'Python' in line:
new_line = line.replace('Python', 'C').strip()
New.append(new_line)
for line in New:
print(line)
【以下回答由 GPT 生成】
你可以使用Python的字符串替换功能来解决这个问题。下面是具体的解决方案:
with open('source_code.txt', 'r') as f:
source_code = f.read()
with open('document.txt', 'r') as f:
document = f.read()
source_code = source_code.replace('Python', 'C')
document = document.replace('Python', 'C')
with open('new_source_code.txt', 'w') as f:
f.write(source_code)
with open('new_document.txt', 'w') as f:
f.write(document)
这样,你就可以成功将源代码和文档中的"Python"替换为"C"。请注意,替换后的文件将保存在当前工作目录中的名为"new_source_code.txt"和"new_document.txt"的文件中。
【相关推荐】