2014-04-03 78 views
1
for line in sourcefile.splitlines(): 
    for l in targetfile.splitlines(): 
     if line in targetfile: 
     sourcefile.replace(line, l) 

print sourcefile 

当我运行代码时,我得到的源文件没有更改。它在for looo之前的状态下打印文件。我怎样才能得到替换结果的源文件。如何在循环中将结果打印到文件中

回答

2

replace()不会修改到位的字符串,它返回一个新的字符串:

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

返回字符串s的通过更换新的子串老 所有出现的副本。

用途:

sourcefile = sourcefile.replace(line, l) 

演示:

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