2014-04-03 5 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' 
관련 문제