Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a built-in or more Pythonic way to try to parse a string to an integer

I had to write the following function to fail gracefully when trying to parse a string to an integer. I would imagine Python has something built in to do this, but I can't find it. If not, is there a more Pythonic way of doing this that doesn't require a separate function?

def try_parse_int(s, base=10, val=None):   try:     return int(s, base)   except ValueError:     return val 

The solution I ended up using was a modification of @sharjeel's answer. The following is functionally identical, but, I think, more readable.

def ignore_exception(exception=Exception, default_val=None):   """Returns a decorator that ignores an exception raised by the function it   decorates.    Using it as a decorator:      @ignore_exception(ValueError)     def my_function():       pass    Using it as a function wrapper:      int_try_parse = ignore_exception(ValueError)(int)   """   def decorator(function):     def wrapper(*args, **kwargs):       try:         return function(*args, **kwargs)       except exception:         return default_val     return wrapper   return decorator 
like image 674
Chris Calo Avatar asked Feb 14 '10 19:02

Chris Calo


People also ask

How do you parse an int from a string in Python?

Parse int to string in Python We can use the inbuilt str() function to parse Python int to String to convert an integer to String. Parsing is the same as converting in programming.

Can we convert string to int in Python?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.


1 Answers

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 
like image 182
sharjeel Avatar answered Sep 21 '22 20:09

sharjeel