1、将文本中的所有d替换为QQ
[root@PC1 test3]# ls a.txt test.py [root@PC1 test3]# cat a.txt erg iuy dfg fdf er4 435 dft 34f cgd err [root@PC1 test3]# cat test.py #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: i = i.replace("d", "QQ") out_file.write(i) in_file.close() out_file.close() [root@PC1 test3]# python test.py [root@PC1 test3]# ls a.txt result.txt test.py [root@PC1 test3]# cat result.txt erg iuy QQfg fQQf er4 435 QQft 34f cgQQ err
2、仅替换第一个匹配的字符
[root@PC1 test3]# ls a.txt test.py [root@PC1 test3]# cat a.txt erg iuy dfg fdf er4 435 dft 34f cgd err [root@PC1 test3]# cat test.py #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in lines: i = i.replace("d", "QQ", 1) out_file.write(i) in_file.close() out_file.close() [root@PC1 test3]# python test.py [root@PC1 test3]# ls a.txt result.txt test.py [root@PC1 test3]# cat result.txt erg iuy QQfg fdf er4 435 QQft 34f cgQQ err