msksantosh
msksantosh

Reputation: 399

Highlight parts of a string if present in a list of words

I am trying to highlight parts of a Python string if the part is present in a list of 2-character words. When the 2-character words are spread apart, I am able to achieve what is needed, but I am not able to do it when the two words occur simultaneously in the string. Here is what I have so far:

r = ''
lofw = ['GO', 'IS', 'OD']
mystr1 = 'HISTORICAL'
pre = '<span style="color: red">'
post = '</span>'
for i in range(0, len(mystr1)-1):
    t = mystr1[i:i+2]
    if t in lofw:
        r = r[:-1] + pre + t + post            
    else:
        r = r[:-1] + t

This code works when there are no consecutive words from the list of words.

However, when there are consecutive words, it throws unwanted results. For example:

mystr2 = 'HISGODTORICAL'

Upvotes: 0

Views: 330

Answers (1)

Tomerikoo
Tomerikoo

Reputation: 19414

A simpler approach would be to use str's replace method:

lofw = ['GO','IS','OD']
mystr1 = 'HISTORICAL'

r = mystr1
pre = '<span style="color: red">'
post =  '</span>'
for sub in lofw:
    r = r.replace(sub, pre + sub + post)

For HISTORICAL this gives:

H<span style="color: red">IS</span>TORICAL

And for HISGODTORICAL this gives:

H<span style="color: red">IS</span><span style="color: red">GO</span>DTORICAL

If the immediate closing and opening of tags bothers you, you can add this after the loop:

r = r.replace(post+pre, "")

So now for HISGODTORICAL we will get:

H<span style="color: red">ISGO</span>DTORICAL

Upvotes: 2

Related Questions