Python String to Int Or None

Use the fact that it generates an exception:

try:
  variable = int(stringToInt)
except ValueError:
  variable = None

This has the pleasant side-effect of binding variable to None for other common errors: stringToInt='ZZTop', for example.


If you want a one-liner like you've attempted, go with this:

variable = int(stringToInt) if stringToInt else None

This will assign variable to int(stringToInt) only if is not empty AND is "numeric". If, for example stringToInt is 'mystring', a ValueError will be raised.

To avoid ValueErrors, so long as you're not making a generator expression, use a try-except:

try:
    variable = int(stringToInt)
except ValueError:
    variable = None

I think this is the clearest way:

variable = int(stringToInt) if stringToInt.isdigit() else None

Here are some options:

Catch the exception and handle it:

try:
    variable = int(stringToInt)
except ValueError, e:
    variable = None

It's not really that exceptional, account for it:

   variable = None
   if not stringToInt.isdigit():
       variable = int(stringtoInt)

Tags:

Python