Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/360.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用多个值替换python方法_Python_Python 2.7_Python 3.x_Replace - Fatal编程技术网

用多个值替换python方法

用多个值替换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

我有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 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)