title: Change substrings with multiple values using offset and length
body: <p>I am working on pulling data from OpenCalais API and here are the details:</p>
  
  <p>Input: Some paragraph (a string e.g. "Barack Obama is the President of United States." Also, what gets returned is some instance variables with offsets and lengths but not necessarily in order of occurrence. </p>
  
  <p>Output (I want):  Same string but with the identified entity instances with hyperlinks (which is also a string) i.e. </p>
  
  <pre><code>output="&lt;a href="https://en.wikipedia.org/Barack_Obama"&gt; Barack Obama &lt;/a&gt; is the President of ""&lt;a href="https://en.wikipedia.org/United_States"&gt; United States. &lt;/a&gt;"
  </code></pre>
  
  <p>BUT IT IS A PYTHON QUESTION REALLY. </p>
  
  <p>This is what I have</p>
  
  <pre><code>#API CALLS ABOVE WHICH IS NOT RELEVANT. 
  
  output=input
  for x in range(0,result.print_entities()):
      print len(result.entities[x]["instances"])
      previdx=0
      idx=0
      for y in range(0,len(result.entities[x]["instances"])):
  
          try: 
              url= "https://permid.org/1-" + result.entities[x]['resolutions'][0]['permid']
  
          except:
              url="https://en.wikipedia.org/wiki/"+result.entities[x]    ["name"].replace(" ", "_")
  
          print "Generating wiki page link"
          print url+"\n"
  
   #THE PROBLEM STARTS HERE
  
           offsetstr=result.entities[x]["instances"][y]["offset"]
           lenstr=result.entities[x]["instances"][y]["length"]
  
           output=output[:offsetstr]+"&lt;a href=" + url + "&gt;" +   output[offsetstr:offsetstr+lenstr] + "&lt;/a&gt;" + output[offsetstr+lenstr:]
  
  print output
  </code></pre>
  
  <p>Now the issue is, if you read the code properly you'll know that after the first iteration, the output string changes - therefore for subsequent iterations, the offset values no longer applies in the same manner. So, I cannot make the expected change. </p>
  
  <p>Basically trying to get:</p>
  
  <pre><code>input = "Barack Obama is the President of United States"
  
  output= "&lt;a href="https://en.wikipedia.org/Barack_Obama"&gt; Barack Obama &lt;/a&gt; is the President of ""&lt;a href="https://en.wikipedia.org/United_States"&gt; United States. &lt;/a&gt;." 
  </code></pre>
  
  <p>How can it be done, I wonder. Tried splicing n dicing but string just gets garbled. </p>