简体   繁体   English

Python-处理值错误

[英]Python - Handling value errors

I am running an external function which should return a string - sometimes, however, this function fails and the string is empty. 我正在运行一个应返回字符串的外部函数-有时,此函数失败并且字符串为空。 The behaviour I would like is "if the string is empty(ie a value error will occur) instead print a '?' 我想要的行为是“如果字符串为空(即,将发生值错误),而不是打印'?' string to my CSV). 字符串到我的CSV)。

Here is my code : 这是我的代码:

    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 

Here is a sample of the bug I am encountering : 这是我遇到的错误的示例:

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

In this case, instead of an error I would like to save a '?' 在这种情况下,我想保存一个“?”而不是错误。 in outrank2. 排名第二。 How can I do this? 我怎样才能做到这一点?

you could wrap that in a try-except 您可以将其包装在try-except中

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

Use try, except method to check for value error. 使用try,除了方法检查值错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM