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.
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).
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.
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.
Empty strings are considered false.
if string: # String is not empty. else: # String is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With