Safe casting in python
I do realize that this is an old post, but this might be helpful to some one.
x = int(word) if word.isdigit() else None
Think not, but you may implement your own:
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0