首页 > 解决方案 > 选择列表中包含的子字符串(没有语法字符)

问题描述

我正在尝试查找和格式化列表中包含的单词。

以下是我尝试过的:

word_list = ['Penny', 'cat', 'carnival']

example_string= "I took my dog Penny and my cat, to the carnival."

formatted_text = " ".join(["<b>{}</b>".format(word) if word.strip(' , . ; :;\ " ()[]{}') in word_list else word for (i, word) in enumerate(example_string.split(" "))])

输出:我带着我的狗Penny和我的狂欢节。

期望的输出:我带着我的狗Penny和我的狂欢节

基本上我想迭代字符串中的每个单词,如果单词在列表中,则对其进行格式化,而不格式化句点、逗号、引号等标点符号。有没有办法做到这一点?

标签: python

解决方案


尝试:-

word_list = ['Penny', 'cat', 'carnival']

example_string = "I took my dog Penny and my cat, to the carnival."

for x in word_list:
    example_string = example_string.replace(x, "<b>" + x + "</b>")

print(example_string)

输出:-

I took my dog <b>Penny</b> and my <b>cat</b>, to the <b>carnival</b>.

在浏览器上查看时:-

我带着我的狗Penny和我的狂欢节


推荐阅读