首页 > 解决方案 > 如果使用 python regex 找到特定字符串,则突出显示整行

问题描述

下面是我的输入字符串。

This is my world. \nI don't like food. \nMy world is my mom.

如果我在输入字符串中找到一个字符串“world”,那么在我打印它时应该突出显示整行。

预期输出。

这是我的世界。 我不喜欢食物。 我的世界是我的妈妈。

标签: python

解决方案


您可以执行以下操作:

from colorama import Fore

my_word = 'world'
my_string = "This is my world. \nI don't like food. \nMy world is my mom."
# this will split the string on new lines
lines = my_string.split('\n')

for line in lines:
    if my_word in line.lower():
        print(f'{Fore.BLUE}{line}')
    else:
        print(line)

推荐阅读