【问题标题】:check for substring is not working [duplicate]检查子字符串不起作用[重复]
【发布时间】:2016-05-25 15:47:00
【问题描述】:

我想检查一个子字母,所以我写了这段代码(Python 2.7):

print text
if ('e' or 'E') in text:
    text = "%s"%float(text)
    print text

按照here的建议。

文本是一个变化的变量,目前它的值是:0E-7

但是这不起作用。 当我调试时,它会跳过 if 块。

为什么条件为假?

【问题讨论】:

    标签: python


    【解决方案1】:

    您的代码要问的是“('e' or 'E') 中的值是 text 吗?”当您评估('e' or 'E') 时,您会得到'e'。这是修复:

    if ('e' in text) or ('E' in text):
    

    【讨论】:

      【解决方案2】:

      ('e' or 'E') 的计算结果为 'e'。所以你正在测试if 'e' in text:,这不是真的,因为0E-7 中的E 是大写的。

      您可以在此处以交互方式查看它:

      >>> text = '0E-7'                  # note that E is uppercase
      >>> ('e' or 'E') in text           # why is this false?
      False
      >>> ('E' or 'e') in text           # but true here?
      True
      >>> ('e' or 'E')                   # aha! 'or' returns the first truthy value
      'e'
      >>> 'e' in text.lower()            # this fixes it
      True
      >>> any(c in text for c in 'eE')   # another possible fix
      True
      >>> not set(text).isdisjoint('eE') # yet another way to do it
      True
      

      【讨论】:

      • ('e' or 'E') 计算结果为 'e',因为 or 接受第一个值,如果它是“真实的”
      • @jcfollower:是的,我不敢相信我犯了那个错误。当你连续几个月被驱逐到 vbscript 时,就会发生这种情况,你开始发明两种语言都不存在的语义。
      【解决方案3】:

      ('e' or 'E') 是一个布尔表达式,它的计算结果为'e'

      我的建议是:

      if any(char in text for char in ('e', 'E')):
          # ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-05-09
        • 2020-07-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-04
        • 2018-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多