Simd
Simd

Reputation: 21333

How to write multiple try/excepts efficiently

I quote often want to try to convert values to int and if they can't be converted, set them to some default value. For example:

try:
    a = int(a)
except:
    a = "Blank"
try:
    b = int(b)
except:
    b = "Blank"
try:
    c = int(c)
except:
    c = "Blank"

Can this be written more efficiently in Python rather than having to write out every try and except?

Upvotes: 0

Views: 51

Answers (1)

James
James

Reputation: 2721

I'd simply use a function:

def int_with_default(i):
    try:
        return int(i)
    except ValueError:
        return "Blank"

a = int_with_default(a)
b = int_with_default(b)
c = int_with_default(c)

If necessary, you can always add a second argument that tells what the default value should be if you don't want to use "Blank" every time.

Upvotes: 4

Related Questions