Python - 处理值错误 [英] Python - Handling value errors

查看:191
本文介绍了Python - 处理值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



这是我的代码:

  outlist = output.split('\r\\\
')#splitting 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])$ ​​b $ b print str(outlist [2])
csvout .writerow([str(outlist [0]),str(outrank1),str(outrank2)])#写,错误在这里

以下是我遇到的错误的示例:

 追溯(最近的呼叫最后): 
文件Methods.py,第24行< module>
outrank2 = outlist [2] [outlist [2] .index(':')+ 1:]
ValueError :未找到子字符串

在这种情况下,我想要保存一个'?'在outrank2。我该怎么做?

解决方案

p>

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


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(i.e a value error will occur) instead print a '?' string to my 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:
  outrank2 = outlist[2][outlist[2].index(':')+1:]
except ValueError:
  outrank2 = "?"

这篇关于Python - 处理值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆