Search code examples
pythonstringpython-3.xsearchstring-concatenation

Python: Surrounding part of a string with other strings?


I have a string like this

the gray fox

and I'd like to surround the word gray with the strings <b> and </b>. What is the most effective (and preferred) way to do this in Python?

(Context: I am building an application with a search function and I'd like to highlight the text in the search results that match the text entered by the user)

Grateful for help and with kind regards, Tord


Solution

  • If you only need to do this with one word, use str.replace:

    sentence = "the gray fox"
    new = sentence.replace('gray', '<b>gray</b>')
    print(new) # the <b>gray</b> fox
    

    If you need to do this with more than one word, use re.sub:

    from re import sub
    sentence = "the gray fox"
    new = sub('(gray)', r'<b>\1</b>', sentence)
    print(new) # the <b>gray</b> fox