How do you represent an empty string in Python?

In some applications, it is compulsory to fill data into an input field. In such cases, they are marked with an asterisk *. Have you ever thought that how is this implemented in the backend? In this article, we will cover various different ways of checking whether an input string is empty or not in Python.

In a simple form on any website, when a user tries to fill in the next field of data without filling the compulsory field or when the user tries to Submit/Save the page/form without filling in the compulsory field(s), it throws a warning which indicates that one/more of the compulsory fields haven't been filled.

This is usually implemented by checking if the data entered by the user is empty or not.

In Python, this could be done in many ways. They are listed below:


1. Using the not operator with the if condition

The Programming Recommendations (PEP 8) suggests that the not operator could be used in conjunction with the if condition, when the data type of the variable being checked for emptiness is known beforehand.

This can be used for lists and tuples as well. A non-empty string evaluates to True when used with an if condition and an empty string evaluate to False. So we can use the if condition for checking whether a given string is empty or not. We can also use it with the not operator which negates the output, hence it makes it more logical if we have to check for an empty string that we use the not keyword with it. So if a string is empty, it returns False, and with not operator it will return True.

Let's take an example and see,

my_string = ''
if not my_string:
    print("The string is empty")
else:
    print("The string is not empty")

Output:

The string is empty

Here is another example showing how a non-empty string is evaluated.

my_string = 'Studytonight'
if not my_string:
    print("The string is empty")
else:
    print("The string is not empty")

Output:

The string is not empty

So, you can use a simple if-else condition too, but it makes more sense code-wise to use the not operator if you have to check for an empty string. Using not operator with the string will return True if the string is empty.


2. Using the strip method

Sometimes, a string might contain blank spaces, which makes it non-empty. Hence while checking for an empty string we also need to check whether the string has only spaces. This can be done using the strip method.

Let's take an example where we will be using the strip method to remove the empty spaces from the given string and will then check if it is empty or not.

def check_for_Blanks(myString):
    # myString is not None AND myString is not empty or blank
    if myString and myString.strip(): 
        return False    
    # myString is None OR myString is empty or blank
    return True 

print(check_for_Blanks('  '))
print(check_for_Blanks(''))
print(check_for_Blanks(None))
print(check_for_Blanks(' Studytonight '))

Output:

True
True
True
False

The above code can also be written as follows(more PYTHONIC way), which would give the same output as the above code,

def check_for_Blanks (myString):
    return not (myString and myString.strip())

print(check_for_Blanks('  '))
print(check_for_Blanks('')) 
print(check_for_Blanks(None))
print(check_for_Blanks(' Studytonight '))

3. Using the __eq__ method

The dunder basically means methods that have double underscores before and after their names.

myString = 'StudyTonight'
if "".__eq__(myString):
    print("Empty string")
else:
    print("Non-empty string")

Output:

Non-empty string

Let's run the above code with an empty string,

myString = ''
if "".__eq__(myString):
    print("Empty string")
else:
    print("Non-empty string")

Output:

Empty string

4. Using the len method

The len method gives the length of the input string and it indicates if the string is non-empty when the length of the string is greater than 0.

myString = 'Studytonight'
if len(myString) == 0:
    print("Empty String")
else:
    print("Non-empty String")

Output:

Non-empty String

5. Using the strip method only

The strip method is usually used to remove blank spaces present in a string. Usually, if a string has only blank spaces it is considered as empty but it may or may not be considered empty depending on the use case. In our case, we will consider a string with only empty spaces as empty.

myString = '      '
if myString.strip():
    print("It is neither empty nor blank")
else:
    print("It is either empty or blank")

Output:

It is either empty or blank

Let's take another example:

myString = ' Studytonight      '
if myString.strip():
    print("It is neither empty nor blank")
else:
    print("It is either empty or blank")

Output:

It is neither empty nor blank

Note: Strings being empty and strings being blank are two different things. An empty string is when the string doesn't have any character, whitespace whatsoever. On the other hand, a blank string means a string that has multiple white spaces or tab spaces. In the above example, both the conditions are being checked for.


Conclusion

In this post, we saw how a string can be checked for being empty or full of whitespaces using various different ways in python. If you think we missed something, do share your way of doing it in the comment section below.

You may also like:

  • String in Python
  • How to Create a long multi-line String in Python
  • Python String capitalize()
  • How to Convert String to Character Array in Python

How do you represent an empty string?

An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null . It can be described as the absence of a string instance.

How do you represent empty in Python?

[] This denotes an empty list. So, by comparing our list object to [], we can determine whether the list is empty or not.

How do you handle an empty string in Python?

Use len to Check if a String in Empty in Python # Using len() To Check if a String is Empty string = '' if len(string) == 0: print("Empty string!") else: print("Not empty string!") # Returns # Empty string! Keep in mind that this only checks if a string is truly empty.

How do you declare an empty string variable in Python?

Defining empty variables in Python is straightforward. If you wish to define a placeholder for a missing value that will not be used for calculations, you can define an empty variable using the None keyword. This is useful because it clearly indicates that the value for a variable is missing or not valid.