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?
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.
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 ValueError
s, so long as you’re not making a generator expression, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = 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)
I think this is the clearest way:
variable = int(stringToInt) if stringToInt.isdigit() else 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)
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?
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 ValueError
s, so long as you’re not making a generator expression, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = 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)
I think this is the clearest way:
variable = int(stringToInt) if stringToInt.isdigit() else 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)