Python String to Int Or None

Question:

Learning Python and a little bit stuck.

I’m trying to set a variable to equal int(stringToInt) or if the string is empty set to None.

I tried to do variable = int(stringToInt) or None but if the string is empty it will error instead of just setting it to None.

Do you know any way around this?

Asked By: user2686811

||

Answers:

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.

Answered By: Robᵩ

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
Answered By: That1Guy

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)
Answered By: Brian Cain

I think this is the clearest way:

variable = int(stringToInt) if stringToInt.isdigit() else None
Answered By: moliware

this will parse stringToInt to int if it’s valid and return original value if it’s ” or None

variable = stringToInt and int(stringToInt)
Answered By: Ali Eb
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.