更新时间:2022-10-18 23:36:28
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 = "?"