variable - python return empty string

Most elegant way to check if the string is empty in Python? (15)

Does Python have something like an empty string variable where you can do?:

if myString == string.empty:

Regardless what's the most elegant way to check for empty string values? I find hard coding "" every time for checking an empty string not as good.

I find hardcoding(sic) "" every time for checking an empty string not as good.

Clean code approach

Doing this: foo == "" is very bad practice. "" is a magical value. You should never check against magical values (more commonly known as magical numbers)

What you should do is compare to a descriptive variable name.

Descriptive variable names

One may think that "empty_string" is a descriptive variable name. It isn't.

Before you go and do empty_string = "" and think you have a great variable name to compare to. This is not what "descriptive variable name" means.

A good descriptive variable name is based on its context. You have to think about what the empty string is.

  • Where does it come from.
  • Why is it there.
  • Why do you need to check for it.

Simple form field example

You are building a form where a user can enter values. You want to check if the user wrote something or not.

A good variable name may be not_filled_in

This makes the code very readable

if == not_filled_in:
    raise ValueError("We need your name")

Thorough CSV parsing example

You are parsing CSV files and want the empty string to be parsed as None

(Since CSV is entirely text based, it cannot represent None without using predefined keywords)

A good variable name may be CSV_NONE

This makes the code easy to change and adapt if you have a new CSV file that represents None with another string than ""

if csvfield == CSV_NONE:
    csvfield = None

There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.

Compare this to

if csvfield == EMPTY_STRING:
    csvfield = None

The first question here is, Why does the empty string deserve special treatment?

This would tell future coders that an empty string should always be considered as None.

This is because it mixes business logic (What CSV value should be None) with code implementation (What are we actually comparing to)

There needs to be a separation of concern between the two.

if stringname: gives a false when the string is empty. I guess it can't be simpler than this.

Either the following

foo is ''

or even

empty = ''
foo is empty

Empty strings are "falsy" which means they are considered false in a Boolean context, so you can just do this:

if not myString:

This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use myString == "". See the documentation on Truth Value Testing for other values that are false in Boolean contexts.

How about this? Perhaps it's not "the most elegant", but it seems pretty complete and clear:

if (s is None) or (str(s).strip()==""): // STRING s IS "EMPTY"...

I once wrote something similar to Bartek's answer and javascript inspired:

def isNotEmpty(s):
    return bool(s and s.strip())


print isNotEmpty("")    # False
print isNotEmpty("   ") # False
print isNotEmpty("ok")  # True
print isNotEmpty(None)  # False

If you just use

not var1 

it is not possible to difference a variable which is boolean False from an empty string '':

var1 = ''
not var1
> True

var1 = False
not var1
> True

However, if you add a simple condition to your script, the difference is made:

var1  = False
not var1 and var1 != ''
> True

var1 = ''
not var1 and var1 != ''
> False

If you want to differentiate between empty and null strings, I would suggest using if len(string), otherwise, I'd suggest using simply if string as others have said. The caveat about strings full of whitespace still applies though, so don't forget to strip.

Responding to @1290. Sorry, no way to format blocks in comments. The None value is not an empty string in Python, and neither is (spaces). The answer from Andrew Clark is the correct one: if not myString. The answer from @rouble is application-specific and does not answer the OP's question. You will get in trouble if you adopt a peculiar definition of what is a "blank" string. In particular, the standard behavior is that str(None) produces 'None', a non-blank string.

However if you must treat None and (spaces) as "blank" strings, here is a better way:

class weirdstr(str):
    def __new__(cls, content):
        return str.__new__(cls, content if content is not None else '')
    def __nonzero__(self):
        return bool(self.strip())


>>> normal = weirdstr('word')
>>> print normal, bool(normal)
word True

>>> spaces = weirdstr('   ')
>>> print spaces, bool(spaces)

>>> blank = weirdstr('')
>>> print blank, bool(blank)

>>> none = weirdstr(None)
>>> print none, bool(none)

>>> if not spaces:
...     print 'This is a so-called blank string'
This is a so-called blank string

Meets the @rouble requirements while not breaking the expected bool behavior of strings.

Test empty or blank string (shorter way):

if myString.strip():
    print("it's not an empty or blank string")
    print("it's an empty or blank string")

When you are reading file by lines and want to determine, which line is empty, make sure you will use .strip(), because there is new line character in "empty" line:

lines = open("my_file.log", "r").readlines()

for line in lines:
    if not line.strip():

    # your code for non-empty lines

You may have a look at this Assigning empty value or string in Python

This is about comparing strings that are empty. So instead of testing for emptiness with not, you may test is your string is equal to empty string with "" the empty string...

a = ''
b = '   '
a.isspace() -> False
b.isspace() -> True

if my_string is '':

I haven't noticed THAT particular combination in any of the answers. I searched for

is ''

in the answers prior to posting.

 if my_string is '': print ('My string is EMPTY') # **footnote

I think this is what the original poster was trying to get to... something that reads as close to English as possible and follows solid programming practices.

if my_string is '':
    print('My string is EMPTY')
    print(f'My string is {my_string}')

Character for character I think this solution is a good one.

I noted None has entered into the discussion, so adding that and compacting further we get:

if my_string is '': print('My string is Empty')
elif my_string is None : print('My string.... isn\'t')
else: print(f'My string is {my_string}')

str = ""
if not str:
   print "Empty String"
   print "Empty String"