【问题标题】:String checking Python字符串检查 Python
【发布时间】:2013-06-16 13:39:16
【问题描述】:

我有一个代表文件名的字符串,我怎样才能一次检查几个条件?我试过了

if r'.jpg' or r'.png' not in singlefile:

但一直收到误报。

【问题讨论】:

    标签: string python-3.x


    【解决方案1】:

    您的代码等于:

    if (r'.jpg') or (r'.png' not in singlefile):
    

    您可能正在寻找:

    if r'.jpg' not in singlefile or r'.png' not in singlefile:
    

    或者

    if any(part not in singlefile for part in [r'.jpg', r'.png']):
    

    感谢蒂姆·皮茨克:

    他(你)实际上(可能)想要

    if not any(singlefile.endswith(part) for part in [r'.jpg', r'.png'])
    #                     ^^^^^^^^
    

    【讨论】:

    • 对。他实际上(可能)想要if not any(singlefile.endswith(part) for part in [r'.jpg', r'.png'])
    • 是的,使用endswith 可能是最好的解决方案
    【解决方案2】:

    这是因为优先级。以下代码表示。

    # r'.jpg' is constant
    if r'.jpg' or (r'.png' not in singlefile):
    

    如果是常量,或者.png 不在singlefile 中。由于常量始终为真,因此表达式始终为真。

    相反,您可以尝试使用正则表达式来检查任何字符串是否符合模式。

    import re
    if re.match(r"\.(?:jpg|png)$", singlefile):
    

    【讨论】:

    • 我也更喜欢正则表达式进行检查,但你更快。无论如何 +1。
    【解决方案3】:

    您的问题在于您的逻辑 OR 正在检查一个常量和一个变量。

    r'.png'
    

    将始终评估为 True,从而使您的 or 也为 true。

    你必须检查两者,像这样

    if r'.png' not in singlefile or 'r.jpg'  not in singlefile:
        #do stuff
    

    【讨论】:

      【解决方案4】:

      试试这个:

      if r'.jpg' not in singlefile or r'.png' not in singlefile:
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 1970-01-01
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2021-03-12
        • 1970-01-01
        相关资源
        最近更新 更多