for line in sourcefile.splitlines():
for l in targetfile.splitlines():
if line in targetfile:
sourcefile.replace(line, l)
print sourcefile
当我运行代码时,我得到了没有更改的源文件。它以 for looo 之前的状态打印文件。如何在源文件中获取替换的结果。
最佳答案
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'
关于python - for循环后如何将结果打印到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842742/