user10209 user10209 - 8 months ago 45
Python Question

Change color for certain words in a sentence

I have a string in Python.

string ="Marry had. A little lamb"

and a string that contains some words from the first string

part="had. lamb"

I need to print the first string and change color for the words from the second string.

Where I am now.

class c:
blue = '\033[94m'
red = '\033[93m'

string ="Marry had. A little lamb"
part =" had. lamb"

pos= [string.split().index(t) for t in part.split()]
print(pos) # prints [1, 4]
print #prints string in blue needs to print 1 and 4 from pos in red


It looks like you are overcomplicating things. A split to change parts into a list, followed by iterating over the individual words in string and testing if they appear in parts, seems all that's necessary:

>>> partwords = part.split()
>>> for w in string.split():
...   if w in partwords:
...     print,
...   else:
...     print,

Result (and yes, your escape code is for yellow, not for red):

Marry in colour