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?
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 stringToInt
is not empty AND is "numeric". If, for example stringToInt
is 'mystring'
, a ValueError
will be raised. If stringToInt
is empty (''
), it will assign variable
to None
.
To avoid ValueError
s, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = None