【问题标题】:Python: test if any string in a list contains a given text [duplicate]Python:测试列表中的任何字符串是否包含给定文本[重复]
【发布时间】:2020-04-27 04:19:36
【问题描述】:

我必须测试一个字符串列表是否包含至少一个包含给定文本的元素(并且该文本包含引号)。 是否可以在不定义新函数的情况下以紧凑的方式进行?

例如

# Text to find
text = """This is a text containing 'quotes' and "doublequotes""""

# List to test
test_strings = [
    "This is a text",
    """Wow! This is a text containing 'quotes' and "doublequotes"!!!"""
]

显然我可以使用 for 循环来做到这一点,但我一直在寻找可以在一行中运行但仍然可读的东西。

【问题讨论】:

标签: python string iterator


【解决方案1】:

我不觉得引号应该有什么不同,但你可以这样做

strings_with_text = [s for s in test_strings if text in s]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多