Python - 处理值错误 [英] Python - Handling value errors
本文介绍了Python - 处理值错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
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屋!
查看全文