1

I have file 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>

and i wanna with test.python replace in file just string with "img1.jpg" to "img2","img3" etc.

import string
s = open("test.html").read()
s = s.replace('http:localhost/img1.jpg','http:localhost/img2.jpg')
f = open("test2.html", 'w')
f.write(s)
f.close()

but program replace all img1 when i wanna replace all string img1 to img2,img3,img[i+1].

How to do it?

2 Answers 2

1

You can do:

s = s.replace('http:localhost/img1.jpg','http:localhost/img2.jpg',1)

The third param is the max ocurrences to replace.

You can see it in python documentation

Sign up to request clarification or add additional context in comments.

2 Comments

but what to do when i wanna create loop to do it in one program
Just wrap this in a loop: for n in range(s.count("img1.jpg")) and then replace with 'img%d.jpg' % n
0

Assuming what you need is a new file with img1 changed to img1 , img2 , img3 .. so on . The following code should work . You will have to go one line at a time .

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.