Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

None vs Empty String in Python

I have an existing application which connects to a database. It is running under Python 2.7.

The application is inconsistent in the way it uses None and "" to populate variables which do not have a value. I want to make this consistent and try to update the code to one way or the other.

Thinking as a database person I think of None as the same as Null and would assume that would be the correct choice for empty variables but then this causes problems when the application does things like

if variable.upper() == "X":
    #Do something

As this raises an error if the variable is None type.

I can do

if variable is not None and variable.upper() == "X":
    #Do something

But this seems unnecessarily verbose.

Is there a best practice for how this should be handled?

like image 886
George Avatar asked Dec 15 '11 11:12

George


People also ask

Is empty string equal to None?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

What is empty string in Python?

It is valid to have a string of zero characters, written just as '' , called the "empty string". The length of the empty string is 0. The len() function in Python is omnipresent - it's used to retrieve the length of every data type, with string just a first example.

What is the difference between null and empty string in Python?

An empty string is a string instance of zero length, whereas a null string has no value at all.

How do you replace None with empty string in Python?

Simply the str function can be used to perform this particular task because, None also evaluates to a “False” value and hence will not be selected and rather a string converted false which evaluates to empty string is returned.


1 Answers

You could cut down on code slightly by just writing

if variable and variable.upper() == "X":
    #Do something

If the variable is none or empty, then it's equivalent to False.

like image 138
obmarg Avatar answered Oct 01 '22 16:10

obmarg