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

PythonParsingInteger

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

def intTryParse(value):
    try:
        return int(value), True
    except ValueError:
        return value, False

Solution 3 - Python

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.

Solution 4 - Python

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

Solution 5 - Python

I would go for:

def parse_int(s, base=10, val=None):
 if s.isdigit():
  return int(s, base)
 else:
  return val

But it's more or less the same thing.

Solution 6 - Python

No, it is already perfect. The val parameter could be better named default, though.

Documented in the official docs simply as int(x) -- x converted to integer

Solution 7 - Python

int() is the built-in and pythonic way, just like you have there.

It's usually easier and more common to use it directly though:

def show_square(user_input):
  """Example of using int()."""
  try:
    num = int(user_input, 10)
  except ValueError:
    print "Error" # handle not-an-integer case
    # or you may just want to raise an exception here
    # or re-raise the ValueError
  else:
    print "Times two is", num * 2

def another_example(user_input):
  try:
    num = int(user_input, 10)
  except ValueError:
    num = default
  print "Times two is", num * 2

Solution 8 - Python

myList = ['12', '13', '5', 'hope', 'despair', '69','0', '1.2']

myInts = [int(x) for x in myList if x.isdigit()]

Solution 9 - Python

This could be another alternative for parsing string to int

while True:
try:
    n = input("Please enter an integer: ")
    n = int(n)
    break
except ValueError:
    print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")

Solution 10 - Python

def parseint(string):
    result = '0'
    for x in string:
        if x.isdigit():
	    result+=x
	else:
	    return int(result)
    return int(result)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChris CaloView Question on Stackoverflow
Solution 1 - PythonsharjeelView Answer on Stackoverflow
Solution 2 - PythonLukas Ĺ alkauskasView Answer on Stackoverflow
Solution 3 - PythonabyxView Answer on Stackoverflow
Solution 4 - PythonLars BlumbergView Answer on Stackoverflow
Solution 5 - PythonMacarseView Answer on Stackoverflow
Solution 6 - Pythonu0b34a0f6aeView Answer on Stackoverflow
Solution 7 - PythonRoger PateView Answer on Stackoverflow
Solution 8 - PythonMackView Answer on Stackoverflow
Solution 9 - PythonDeepak VermaView Answer on Stackoverflow
Solution 10 - Pythonuser2151391View Answer on Stackoverflow