【问题标题】:Find tuple of strings in string in python [duplicate]在python中的字符串中查找字符串元组[重复]
【发布时间】: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 你说的很对。直到发表评论后,我才注意到问题的“任何地方”部分。
  • 但你已经明白了。

标签: python python-3.x


【解决方案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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2014-02-27
    • 1970-01-01
    • 2023-04-04
    • 2017-04-25
    • 2014-05-09
    • 2020-02-24
    • 1970-01-01
    相关资源
    最近更新 更多