user278618 user278618 - 1 year ago 99
Python Question

Safe casting in python

I have a problem with casting in python.

I c# I can safe cast by keyword as, e.g.:

string word="15";
var x=word as int32// here I get 15

string word="fifteen";
var x=word as int32// here I get null

Has python(3.2) something similar to this?

Answer Source

Think not, but you may implement your own:

def safe_cast(val, to_type, default=None):
        return to_type(val)
    except (ValueError, TypeError):
        return default

safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download