title: insert open and close tags at the positions corresponding to a list of tups
body: <p>I have to mark up a text inserting tags in a string as follows:</p>
  <pre><code>mystring = '123456789'
  postions = [(2,4),(6,8)]
  
  result = '12&lt;tag1&gt;34&lt;/tag1&gt;56&lt;tag2&gt;78&lt;/tag2&gt;9'
  </code></pre>
  <p>positions is a list of tuples that gives the start and end of the tag.
  (In principle the spans of the tags do not overlap)</p>
  <p>I started assumend that I would need all the positions of the tags flatten out:</p>
  <pre><code>import itertools
  pos2 = list(itertools.chain(*positions))
  </code></pre>
  <p>which gives:</p>
  <pre><code>[2, 4, 6, 8]
  </code></pre>
  <p>That allows me to do this:</p>
  <pre><code>stringWithTags= ''
  opentag=True
  nrtag=1
  for j,character in enumerate(mystring):
      i=j+1
      if i in pos2:
          if opentag:
              toadd = character + '&lt;tag' + str(nrtag) +'&gt;' 
          else:
              toadd = character + '&lt;/tag' + str(nrtag) +'&gt;'  
              nrtag = nrtag + 1
          
          stringWithTags = stringWithTags + toadd
          opentag = not(opentag)
          
      else:
          stringWithTags = stringWithTags + character
  
  stringWithTags
  </code></pre>
  <p>that works, but its quite horrible code, and incredible verbose.
  This problem should be well known and there might be out of the box solutions I am not aware of.</p>
  <p>Any suggestions?</p>
  <p>EDIT 1: I also considered my code not water tight because the moment the spans overlap this will not fly and a solution valid in both cases</p>