Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to do a "not None" test in Python for a normal and Unicode empty string?

Tags:

python

string

In Python 2.7, I'm writing a class that calls a function in an API which might, or might not, return an empty string. Furthermore, the empty string might be unicode u"", or non-unicode "". I was wondering what the best way to check for this?

The following code works great for an empty string, but not an empty unicode string:

class FooClass():     string = ...     string = might_return_normal_empty_string_or_unicode_empty_string(string)      # Works for normal empty strings, not unicode:     if string is not None:         print "string is not an empty string." 

Instead I'd have to write it like this to get it to work for unicode:

class BarClass():     string = ...     string = might_return_normal_empty_string_or_unicode_empty_string(string)      # Works for unicode empty strings, not normal:     if string is not u"":         print "string is not an empty string." 

...and like this to get it to work for both empty strings in non-unicode and unicode:

class FooBarClass():     string = ...     string = might_return_normal_empty_string_or_unicode_empty_string(string)      # Works for both normal and unicode empty strings:     if string is not u"" or None:         print "string is not an empty string." 

Is the third method the best way to do this, or is there a better way? I ask because writing a u"" feels a little too hard-coded to me. But if that's the best way to do it, so be it. :) Thanks for any help you can offer.

like image 975
Dave Avatar asked Apr 16 '11 23:04

Dave


People also ask

How do you check if a string is not None in Python?

Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).

How do you check if a string is None or not?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string.

How do you show empty strings in Python?

The len() function returns the length of a string, the number of chars in it. 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.


1 Answers

Empty strings are considered false.

if string:     # String is not empty. else:     # String is empty. 
like image 58
Artur Gaspar Avatar answered Oct 08 '22 02:10

Artur Gaspar