用多个值替换python方法
我有test.html文件用多个值替换python方法,python,python-2.7,python-3.x,replace,Python,Python 2.7,Python 3.x,Replace,我有test.html文件 <p>Just example code</p> <div> <img src="http:localhost/img1.jpg"> </div> <p>Just example code2</p> <div> <img src="http:localhost/img1.jpg"> </div> <p>Just exa
<p>Just example code</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
<p>Just example code2</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
<p>Just example code3</p>
<div>
<img src="http:localhost/img1.jpg">
</div>
但当我想将所有字符串img1替换为img2,img3,img[i+1]时,程序会替换所有img1
怎么做?你可以做:
s = s.replace('http:localhost/img1.jpg','http:localhost/img2.jpg',1)
第三个参数是要替换的最大眼压
您可以在中看到它,假设您需要的是一个新文件,其中img1更改为img1、img2、img3。。等等。下面的代码应该可以工作。你一次只能走一行
i=2
with open("test.html")as f ,open("test2.html",'w') as f1:
for elem in f.readlines():
if 'http:localhost/img' in elem:
f1.write(elem.replace('http:localhost/img1','http:localhost/img%s'%i))
i+=1
else:
f1.write(elem)
但是当我想创建一个循环来在一个程序中实现它时该怎么办呢?只需将它包装在一个循环中:
用于范围内的n(s.count(“img1.jpg”)
,然后替换为'img%d.jpg'%n
i=2
with open("test.html")as f ,open("test2.html",'w') as f1:
for elem in f.readlines():
if 'http:localhost/img' in elem:
f1.write(elem.replace('http:localhost/img1','http:localhost/img%s'%i))
i+=1
else:
f1.write(elem)