在for循环之后,如何在文件中打印结果

2024-10-01 02:38:00 发布

您现在位置:Python中文网/ 问答频道 /正文

for line in sourcefile.splitlines():
   for l in targetfile.splitlines():
      if line in targetfile:
        sourcefile.replace(line, l)

print sourcefile

当我运行代码时,我得到的源文件没有任何更改。它在for looo之前的状态下打印文件。如何在源文件中获取替换的结果


Tags: 代码inforif状态linereplaceprint
1条回答
网友
1楼 · 发布于 2024-10-01 02:38:00

replace()不会就地修改字符串,它会返回一个新字符串:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new.

使用:

sourcefile = sourcefile.replace(line, l)

演示:

>>> s = 'test1'
>>> s.replace('1', '2')
'test2'
>>> s
'test1'
>>> s = s.replace('1', '2')
>>> s
'test2'

相关问题 更多 >