【问题标题】:Python check if any items of a tuple are in a string [duplicate]Python检查元组的任何项目是否在字符串中[重复]
【发布时间】:2012-09-20 15:54:43
【问题描述】:

可能重复:
Check if multiple strings exist in another string
Check to ensure a string does not contain multiple values

所以伙计们。如果我有

example = "1", "2", "3"

如何检查是否有任何项目在字符串中。

【问题讨论】:

    标签: python ubuntu


    【解决方案1】:

    使用any():

    if any(s in some_string for s in example):
        # at least one of the elements is a substring of some_string
    

    【讨论】:

    • 这看起来像是最“Pythonic”的方式。
    • 代码中的“s”是什么。 (对 python 相当陌生。)
    • @user1705279:它是生成器表达式中的变量。它代表example 元组中的每个字符串。
    【解决方案2】:

    一个例子:

    >>> example = "1", 2, "3"
    >>> str in [type(entry) for entry in example]
    

    如果元组中有 str,则返回 True。

    【讨论】:

    • 我认为问题是检查它们是否在一个字符串中,而不是它们中的任何一个是否是一个字符串。
    猜你喜欢
    • 1970-01-01
    • 2021-05-02
    • 2020-11-12
    • 1970-01-01
    • 2017-03-11
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多