python - 如果使用 python regex 找到特定字符串,则突出显示整行
问题描述
下面是我的输入字符串。
This is my world. \nI don't like food. \nMy world is my mom.
如果我在输入字符串中找到一个字符串“world”,那么在我打印它时应该突出显示整行。
预期输出。
这是我的世界。 我不喜欢食物。 我的世界是我的妈妈。
解决方案
您可以执行以下操作:
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)
推荐阅读
- for-loop - 在通道上迭代时出错“范围内的变量太多”
- c++ - 为什么我会收到此警告?“成员 'x' 未在此构造函数中初始化”
- symfony - Symfony3 在 Doctrine2 中保留嵌入形式(违反完整性约束:空字段)
- java - 文本文件中没有可用的内容 Google Drive API v3 Java
- c# - 无法从占位符文本框更新数据库表
- java - 获取文件中两个字符之间的所有子字符串
- iot - 树莓派 2 支持 thingsboard 物联网平台吗?
- java - 如果使用 DataProvider,如何在 TestNG 可发送电子邮件的报告中提供自定义方法名称
- javascript - 使用 js 创建书签
- recursion - 有没有办法在 Kotlin 内部调用匿名函数?