Python-如何突出显示字符串中的单词?

时间:2019-09-24 08:53:16

标签: python string

我正试图编写一个程序来解决单词搜索难题,并向用户展示单词的位置,我想将字符串中所有匹配的单词大写。

例如, 'randomtextfoorandomtext'

变成 'randomtextFOOrandomtext'

我曾考虑过使用列表理解,但是不确定如何使用这种方式。

1 个答案:

答案 0 :(得分:6)

最简单的方法是使用str.replace()方法:

puzzle = 'randomtextfoorandomtext'
word = 'foo'
highlighted = puzzle.replace(word, word.upper())