【问题标题】:check if output returns ValueError检查输出是否返回 ValueError
【发布时间】:2019-11-04 02:52:23
【问题描述】:

我想在 python 字符串中检索字符的索引。但是当找不到字符串时,函数返回ValueError: substring not found

由于我在 if 语句中有函数,它会破坏我的代码。

我如何验证以下代码行的输出是否没有给出ValueError 输出:mystring.index('string I look for')

【问题讨论】:

  • 可以使用try catch捕捉异常
  • 您需要提供示例代码、示例和输出,以便重现问题

标签: python valueerror


【解决方案1】:

你可以先创建一个函数来检查它

def check(s, target):
    if target in s:
           return s.index(target)
    else:
           return None

s = 'Yeah, I\'m gonna take my horse to the old town road'

check(s, 'g')
# 10

或者使用 lambda 函数,如果您打算只使用一次或两次

check = lambda s, t: s.index(t) if t in s else None
s = 'Yeah, I\'m gonna take my horse to the old town road'

check(s, 'old')
# 37

s[37]
# 'o'

【讨论】:

    【解决方案2】:

    您可以使用try except 捕获抛出的异常:

    In [1]: s = "hello world"
    
    In [1]: s = "hello world"
    
    In [2]: s.index("a")
    ---------------------------------------------------------------------------
    ValueError                                Traceback (most recent call last)
    <ipython-input-2-1a10a9a0bcff> in <module>
    ----> 1 s.index("a")
    
    ValueError: substring not found
    
    In [3]: try:
       ...:     s.index("a")
       ...: except ValueError:
       ...:     pass  # or do something else. This means that the character was not found
    

    【讨论】:

      【解决方案3】:

      见 8.3。处理异常here

      TRY / EXCEPT 应该可以解决问题。例如:

      try:
          mystring.index('c')
      except:
          print('substring not found')
      

      如果字符串中存在字符'c',它将返回它的索引,如果不存在,它将执行您指定的操作。在这种情况下,它将打印“未找到子字符串”并继续代码而不破坏它

      这将适用于任何错误。如果您想更具体并针对不同类型的错误执行不同的操作,您还可以按错误类型指定操作...例如

      except ValueError:
          <do something>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-24
        • 2019-01-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多