I guess you are making to complex
import re
# a list of words to format differently
wordsToItalicize = ["italic", "bar"]
# your text
txt = '''foo bar italic bar foo italic bar foo'''
# the default formatting as a reusable dict
defaultFormatting = dict(
font="Skia",
fill=(0, .2, .1, 1)
)
# the italic formatting as a reusable dict
italicFormatting = dict(
font="Times-Italic",
fill=(1, 0, 0, 1)
)
# compile a regex
r = re.compile(f"({'|'.join(wordsToItalicize)})")
# start an empty formatted string
ftxt = FormattedString()
# start loop over all the items with the regex
for item in r.split(txt):
# choose the correct formatting
if item in wordsToItalicize:
settings = italicFormatting
else:
settings = defaultFormatting
# append the text in the formatting text
ftxt.append(item, **settings)
# draw the text
textBox(ftxt, (10, 10, 100, 100))