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?
The most efficient way to check if a string is an integer in Python is to use the str. isdigit() method, as it takes the least time to execute. The str. isdigit() method returns True if the string represents an integer, otherwise False .
To convert a string to an integer you use the handy int() function. For example, if you have a string such as "79" and you insert this like so into the int() function: int("79") you get the result 79 .
None is a data type just like int, float, etc. and only None can be None. You can check out the list of default types available in Python in 8.15.
Use the boolean OR operator to convert NoneType to a string in Python, e.g. result = None or "" . The boolean OR operator will return the value to the right-hand side because the value to the left ( None ) is falsy. Copied!
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
I think this is the clearest way:
variable = int(stringToInt) if stringToInt.isdigit() else None
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With