1

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?

3 Answers 3

4

you could wrap that in a try-except

try:
  outrank2 = outlist[2][outlist[2].index(':')+1:]
except ValueError:
  outrank2 = "?"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

Use try, except method to check for value error.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.