编程语言
首页 > 编程语言> > python 中实现文本中字符串的替换

python 中实现文本中字符串的替换

作者:互联网

 

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

 

标签:test3,txt,python,PC1,file,字符串,py,文本,root
来源: https://www.cnblogs.com/liujiaxin2018/p/16342644.html