【问题标题】:ValueError despite try and exceptValueError 尽管尝试和除外
【发布时间】:2020-10-23 16:42:27
【问题描述】:

我正在使用 try 和 except 来防止 ValueError,但我仍然得到它,我不明白:

if ('Address' and 'Phone') in text_string:
    try:
        pos_1 = text_string.index('Address')
        pos_2 = text_string.index('Phone')
        output['address'] = text_string[pos_1+7:pos_2]
    except ValueError:
        output['address'] = None

我在这里收到 ValueError:

 pos_1 = text_string.index('Address')

但是由于我已经过滤了 if 子句,我应该不会收到 ValueError 消息?

【问题讨论】:

  • 试试if 'Address' in text_string and 'Phone' in text_string:

标签: python-3.x try-catch valueerror except


【解决方案1】:

虽然Nick's 的评论已经解决了这个问题,但是对于新人来说还是有帮助的。

好的,这里的问题在于最初的if 语句。

('Address' and 'Phone') in text_string 等价于'Phone' in text_string,因为在这里,一个非空字符串在逻辑上是True,它是and 和另一个字符串,比如s2,将导致s2

所以,这里的('Address' and 'Phone')'Phone' 相同,因此您只是在text_string 中检查'Phone' 的可用性,因此Value Error

因此代码应该是,

if 'Address' in text_string and 'Phone' in text_string:
    try:
        pos_1 = text_string.index('Address')
        pos_2 = text_string.index('Phone')
        output['address'] = text_string[pos_1+7:pos_2]
    except ValueError:
        output['address'] = None

【讨论】:

    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-03
    • 2019-11-26
    • 1970-01-01
    • 2012-03-12
    相关资源
    最近更新 更多