变量检查中字符串python中的多个子字符串

问题描述 投票:0回答:2

我有以下代码:

check = "red" in string_to_explore

如何复制多个子字符串?

我尝试过:

check = "red|blue" in string_to_explore

但似乎不起作用。

提前致谢,

python python-3.x string find substring
2个回答
0
投票

Python str 方法不接受正则表达式模式,为此使用

re
模块:

import re

text = "foo foo blue foo"
pattern = re.compile(r"red|blue")
check = bool(pattern.search(text))
print(check) # True

0
投票

您可以将列表理解与any一起使用。

string_to_explore="red my friend"
strings="red|blue".split("|")
check = any([x in string_to_explore for x in strings])
print(check)

string_to_explore1="blue my friend"
check1 = any([x in string_to_explore1 for x in strings])
print(check1)

string_to_explore2 = "nothing my friend"
check2 = any([x in string_to_explore2 for x in strings])
print(check2)

# True
# True
# False
© www.soinside.com 2019 - 2024. All rights reserved.