Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a variable is empty in python?

Tags:

python

I am wondering if python has any function such as php empty function (http://php.net/manual/en/function.empty.php) which check if the variable is empty with following criteria

"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) 
like image 601
dextervip Avatar asked May 11 '12 04:05

dextervip


People also ask

How do you know if a variable is empty?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

How do you check if a variable has value in Python?

if str(variable) == [contains text]:

Is none or empty Python?

The None value is not an empty string in Python, and neither is (spaces).


1 Answers

See also this previous answer which recommends the not keyword

How to check if a list is empty in Python?

It generalizes to more than just lists:

>>> a = "" >>> not a True  >>> a = [] >>> not a True  >>> a = 0 >>> not a True  >>> a = 0.0 >>> not a True  >>> a = numpy.array([]) >>> not a True 

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:

>>> a = "0" >>> not a False  >>> a = '0' >>> not int(a) True 
like image 70
kitchenette Avatar answered Oct 10 '22 07:10

kitchenette