'Insert tags in a python string using positions

I have a python string and a tuple/list of tuples representing the position of the subsequence to tag and the name of the tag:

text = "This is an example"
label = (0, 4, "tag1")

# Expected result
> "<tag1>This</tag1> is an example"

Another example:

text = "This is a more complicated example"
labels = [(0, 7, "tag1"),
          (5, 7, "tag2"),
          (10, 14, "tags3")]

# Expected result
> "<tag1>This <tag2>is</tag2></tag1> a <tag3>more</tag3> complicated example"

How to insert a tag at the specified positions?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source