navre3
navre3

Reputation: 35

How to replace multiple instances of a sub string in a long string (html template) with a list of strings in order?

I'm trying to write a text file web document using python (First year uni student learning the basic concepts of python)

Say I have a HTML template like this:

<!DOCTYPEhtml>
<html>
<head>
    <title>News Archive</title>
</head>

<body> 
  <br>
  <ol>

  <!--  Article 1 -->

  <h1>***TITLE***</h1>


  <img src=***IMGURL***  
  <p>***DESCRIPTION***</p>
  <p><strong> Full story: </strong> ***LINK*** </p>
  <p><strong> Dateline: </strong> ***PUBDATE*** </p>
  <br/>
  <!--  Article 2 -->  
  <h1>***TITLE***</h1>
  <img src=***IMGURL***   

  <p>***DESCRIPTION***</p>

  <p><strong> Full story: </strong> ***LINK*** </p>
  <p><strong> Dateline: </strong> ***PUBDATE*** </p>

</body>
</html>

Lets say I want to replace all instances of \*\**TITLE*** with strings in a list in order. Here is the list containing strings:

titles = ['HI', 'HELLO']

How would i replace the first instance of ***TITLE*** with 'HI' and the second instance of \*\**TITLE*** with 'HELLO'?

I've tried this basic for loop but I don't think I have done it correctly (Since I'm only learning basics of python, i think the teacher wants a for-loop)

for tags in range(2):
    html_code = html_template.replace('***TITLE***', titles)

Thanks in advance. (PS: Sorry for terrible formatting, new to stack overflow)

EDIT: Sorry forgot to mention crucial detail...
What if i wanted to create a for loop that replaces for example ***TITLE*** with its respective 2 string list, ***IMGURL*** with its respective 2 string list, ***DESCRIPTION*** with its respective 2 string list, and so on for the rest of the placeholders?

Upvotes: 0

Views: 53

Answers (1)

user2390182
user2390182

Reputation: 73490

You can specify how many occurrences you want to replace:

for t in titles:
    html_template = html_template.replace('***TITLE***', t, 1)

Upvotes: 1

Related Questions