python - for循环后如何将结果打印到文件中

标签 python string python-2.7

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/

相关文章:

excel - 将 worksheet.hide_gridlines(2) 设置为特定范围的单元格

python - ImportError : this is MySQLdb version (1, 2, 4, 'beta' , 4), 但_mysql 是版本 (1, 2, 5, 'final' , 1)

c - 如何对 char 类型进行安全算术

python - 在opencv python中每秒处理一帧

string - go encoding/csv 中引用字符串的奇怪 CSV 结果

Java 最终字符串,C++ 等价物。我的理解正确吗?

python - 如何让两个脚本引用同一个模块

python - 将 Django 1.8 与 Shibboleth 一起使用

python - 在 AWS Lambda 中访问 GET 参数

python - 使用 dateutil 将 'month-day' 格式正确转换为 'month-day-year' 格式