在python中的字符串中查找字符串元组[重复]

Posted

技术标签:

【中文标题】在python中的字符串中查找字符串元组[重复]【英文标题】:Find tuple of strings in string in python [duplicate] 【发布时间】:2018-05-15 14:27:10 【问题描述】:

使用startswith()endswith() 函数可以传递字符串元组,如果任何元素匹配,则返回结果True 例如:

text_to_find = ("string_1", "string2")

test = "string_to_look_in"

if test.startswith(text_to_find ) == True:
     print  ("starts with one of the strings")

是否有类似的命令可以用于元组,用于在字符串中查找字符串 - 即元组中的字符串之一出现在文本中的任何位置。 (而不是例如使用 for 循环,在其中单独查看字符串中的每个项目)。

【问题讨论】:

我建议if any(x in test for x in text_to_find):。测试布尔条件时不需要== True @khelwood “答案”是 if any(x in test for x in text_to_find) "..在文本中任何地方出现的元组中的一个字符串.." @Jean-FrançoisFabre 你说的很对。直到发表评论后,我才注意到问题的“任何地方”部分。 但你已经明白了。 【参考方案1】:

首先,尝试使用any 测试列表中的所有项目。其次,由于您想知道字符串是否包含在文本中的任何位置,您可以使用in。例如:

text_to_find = ("string_1", "string2", "to_look")

test = "string_to_look_in"

if any(s in test for s in text_to_find):
     print  ("contains one of the strings")

【讨论】:

以上是关于在python中的字符串中查找字符串元组[重复]的主要内容,如果未能解决你的问题,请参考以下文章