【问题标题】:Python check if there's any empty string in multiple stringsPython检查多个字符串中是否有空字符串
【发布时间】:2014-06-23 19:21:57
【问题描述】:

我知道这是一个基本问题,但请多多包涵。假设我们下面有 4 个字符串:

a = ''
b = 'apple'
c = 'orange'
d = 'banana'

所以,通常如果我想检查三个字符串 a b c 是否为空,我可以使用 len() 函数。

if len(a) == 0 or len(b) == 0 or len(c) == 0:
    return True

但后来我觉得如果我有很多字符串,像上面这样写太麻烦了。所以,我用了

if not a:
    return True

但是,当我使用上述方法检查多个字符串 b c d 时,它返回 True 我很困惑,因为不是字符串 b c d 其中空。

if not b or c or d:
    return True

发生了什么事?

【问题讨论】:

标签: python string if-statement


【解决方案1】:

not 运算符的 precedence 高于 or。

return not b or not c or not d

应该可以。

【讨论】:

    【解决方案2】:

    问题在于这一行:

    if not b or c or d:
    

    您需要为每个字符串包含“非”条件。所以:

    if not b or not c or not d:
    

    你也可以这样做:

        return '' in [a, b, c, d]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      • 2015-06-10
      • 2011-03-24
      • 2023-03-31
      相关资源
      最近更新 更多