Is there a built-in or more Pythonic way to try to parse a string to an integer
This is a pretty regular scenario so I've written an "ignore_exception" decorator that works for all kinds of functions which throw exceptions instead of failing gracefully:
def ignore_exception(IgnoreException=Exception,DefaultVal=None):
""" Decorator for ignoring exception from a function
e.g. @ignore_exception(DivideByZero)
e.g.2. ignore_exception(DivideByZero)(Divide)(2/0)
"""
def dec(function):
def _dec(*args, **kwargs):
try:
return function(*args, **kwargs)
except IgnoreException:
return DefaultVal
return _dec
return dec
Usage in your case:
sint = ignore_exception(ValueError)(int)
print sint("Hello World") # prints none
print sint("1340") # prints 1340
def intTryParse(value):
try:
return int(value), True
except ValueError:
return value, False
That's the pythonic way. In python, it's customary to use EAFP style - Easier to Ask Forgiveness than Permission.
That means you'd try first, and then clean up the mess if necessary.
Actually there is a "built-in", single line solution that doesn't require to introduce a new function. As I hoped to find such an answer here, I'm adding it:
>>> s = "123"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
123
>>> s = "abc"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
>>> s = ""
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
>>> s = "1a"
>>> i = int(s) if s.isdigit() else None
>>> print(i)
None
See also https://docs.python.org/3/library/stdtypes.html#str.isdigit