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.
this will parse stringToInt to int if it's valid and return original value if it's '' or None
variable = stringToInt and int(stringToInt)
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
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.
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)