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

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Apr 3 04:15:46 CEST 2007


On Mon, 02 Apr 2007 13:48:30 -0700, Steven Howe wrote:

> how about just testing it's length?
>  >>> from types import StringType
> 
> def stringTest(x):
> ...     if type(x) == StringType:
> ...             if len(x) == 0:
> ...                     print 'Empty String'
> ...             else:
> ...                     print 'Not Empty String'
> ...     else:
> ...             print 'value not String Type'


Too complicated. You don't need to import StringType, nor do you need
to explicitly ask for the length. Worse, you reject anything that isn't
*precisely* a string. Other string classes, like Unicode and subclasses,
are wrongly rejected. Try this instead:

def stringTest(x):
    if isinstance(x, basestr):
        if x:
            print "Not an empty string."
        else:
            print "An empty string."
    else:
        print "Not a string."


Here's an even shorter version, saving one line.

def stringTest(x):
    if not isinstance(x, basestring):
        print "Not a string."
    elif x:
        print "Not an empty string."
    else:
        print "An empty string."

And here's an even shorter version.

def stringTest(x):
    if not isinstance(x, basestring):
        print "Not a string."
    else:
        print {True: "Not a", False: "A"}[bool(x)] + "n empty string."


Notice, though, that shorter code is not always better.



-- 
Steven D'Aprano 




More information about the Python-list mailing list