Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python String to Int Or None

Tags:

python

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?

like image 499
user2686811 Avatar asked Sep 04 '13 20:09

user2686811


People also ask

How do you check if a string can be converted to int in Python?

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 .

How do you convert an empty string to an int in Python?

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 .

Can int be None in Python?

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.

How do you cast None in Python?

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!


2 Answers

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 
like image 116
That1Guy Avatar answered Sep 18 '22 22:09

That1Guy


I think this is the clearest way:

variable = int(stringToInt) if stringToInt.isdigit() else None 
like image 39
moliware Avatar answered Sep 18 '22 22:09

moliware