【问题标题】:Python - Handling value errorsPython - 处理值错误
【发布时间】:2014-02-27 21:36:13
【问题描述】:

我正在运行一个应该返回一个字符串的外部函数——然而,有时这个函数会失败并且字符串是空的。我想要的行为是“如果字符串为空(即会发生值错误)而不是打印'?'字符串到我的 CSV)。

这是我的代码:

    outlist = output.split('\r\n') #splitting the string
    outrank1 = outlist[1][outlist[1].index(':')+1:]
    outrank2 = outlist[2][outlist[2].index(':')+1:]
    print outrank1
    print outrank2
    print str(outlist[0])
    print str(outlist[1])
    print str(outlist[2])
    csvout.writerow([str(outlist[0]), str(outrank1), str(outrank2)]) #writing,error here 

这是我遇到的错误示例:

Traceback (most recent call last):
  File "Methods.py", line 24, in <module>
    outrank2 = outlist[2][outlist[2].index(':')+1:]
ValueError: substring not found

在这种情况下,我想保存一个“?”而不是错误超过排名2。我该怎么做?

【问题讨论】:

    标签: python debugging csv error-handling split


    【解决方案1】:

    你可以把它包装在一个 try-except 中

    try:
      outrank2 = outlist[2][outlist[2].index(':')+1:]
    except ValueError:
      outrank2 = "?"
    

    【讨论】:

      【解决方案2】:
      try:
          outrank1 = outlist[1][outlist[1].index(':')+1:]
      except ValueError:
          outrank1 = "?"
      

      【讨论】:

        【解决方案3】:

        使用try,除了检查值错误的方法。

        try:
          outrank2 = outlist[2][outlist[2].index(':')+1:]
        except ValueError:
          outrank2 = "?"
        

        【讨论】:

          猜你喜欢
          • 2021-01-18
          • 1970-01-01
          • 2016-09-13
          • 2015-11-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多