44

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?

user2686811
  • 579
  • 2
  • 6
  • 11
  • 3
    Define 'empty'? Is `' '` empty? Any white space? – dawg Sep 04 '13 at 21:11
  • This is almost the reverse question to [Python: most idiomatic way to convert None to empty string?](https://stackoverflow.com/questions/1034573/python-most-idiomatic-way-to-convert-none-to-empty-string) – smci Jul 27 '19 at 01:54

5 Answers5

71

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
Damian Yerrick
  • 4,602
  • 2
  • 26
  • 64
That1Guy
  • 7,075
  • 4
  • 47
  • 59
  • 5
    This bears explanation in detail for a novice. – Marcin Sep 04 '13 at 21:02
  • 7
    The one-liner returns None when stringToInt = 0. Better would be: `variable = int(stringToInt) if stringToInt is not None else None`. – kadee Aug 23 '18 at 08:35
  • @kadee if `stringToInt` is `0` then it is not a string. You're right though, that the one-liner will only work for strings, which was what the question was asking about. Also, your proposed solution wouldn't work for empty strings and would raise the same exception OP was receiving. =) – That1Guy Aug 23 '18 at 15:25
30

I think this is the clearest way:

variable = int(stringToInt) if stringToInt.isdigit() else None
moliware
  • 10,160
  • 3
  • 37
  • 47
  • 2
    This won't work where stringToInt is None as that doesn't have an isdigit() – Damian Mar 29 '16 at 11:36
  • 5
    You can strengthen it with check for None like `variable = int(stringToInt) if stringToInt and stringToInt.isdigit() else None` – fizmax Apr 16 '18 at 13:33
  • 4
    isdigit is unsafe because it recognizes unicode power-of-2, ² , as a digit. isdecimal is the safe way. So: `variable = int(stringToInt) if stringToInt and stringToInt.isdecimal() else None` – Dave Rove Jul 16 '20 at 11:27
19

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.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • 1
    I think this solution is probably the best as it will handle situations where the string contains non-digit characters as well. – Brandon Buck Sep 04 '13 at 21:04
  • 1
    Doesn't handle `None`, as calling `int()` on it raises another exception: _"TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'"_ – Nickolay Nov 26 '19 at 11:36
4

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)
Brian Cain
  • 14,403
  • 3
  • 50
  • 88
3

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

variable = stringToInt and int(stringToInt)
Ali Eb
  • 71
  • 6