How can i compare a string which is non null and empty

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Apr 2 21:36:36 CEST 2007


Plissken.s at gmail.com a écrit :
> Hi,
> 
> how can i compare a string which is non null and empty?

Compare with what ?-)

> 
> i look thru the string methods here, but cant find one which does it?
> 
> http://docs.python.org/lib/string-methods.html#string-methods
> 
> In java,I do this:
> if (str != null) && (!str.equals("")) ....
> 
> how can i do that in python?
> 
1/ don't use 'str' as an identifier as it will shadow the builtin str type.

2/ just test:

if some_str:
   # code here

In a boolean context, both the None object (the closer equivalent to 
Java's 'null') and an empty string will eval to False (FWIW, so will do 
an empty list, an empty tuple, an empty set, an empty dict, and a 
numeric zero).

FWIW, Python allows (and encourage where it makes sens) operator 
overloading. cf:
http://docs.python.org/ref/specialnames.html

HTH



More information about the Python-list mailing list