Signup/Sign In

How to check if string is empty in Python?

Posted in Programming   LAST UPDATED: MAY 3, 2023

    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 to check 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 in 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 To Check if a String is Empty in Python

    The Programming Recommendations (PEP 8) suggest that the not an 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 a 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 the 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 the operator with the string will return True if the string is empty.


    2. Using the strip method To Check if a String is Empty in Python

    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 To Check if a String is Empty in Python

    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 To Check if a String is Empty in Python

    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 To Check if a String is Empty in Python

    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 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, or 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 conditions are being checked for.

    Conclusion

    Checking for empty lines and whitespace is a frequent Python computing prerequisite. We saw in this article how to verify an empty string in Python using the len() function, comparing it to an empty string literal, and using the string's boolean value. We also looked at how to use the string function isspace to check for spaces( ). If you believe we overlooked something or have an alternative approach, please share it in the comments area below. Incorporating these methods into your Python code can improve the robustness and efficiency of your applications.

    Frequently Asked Questions(FAQs)

    1. What is an empty string in Python?

    An empty string in Python is a string with no characters or a length of zero. It is denoted by two quotes with nothing in between them: "".

    2. How can I check if a string is empty in Python?

    You can check if a string is empty in Python using the not operator, which returns True if the string is empty and False otherwise. Here's an example code snippet:

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

    3. What is the len() function in Python and how can it be used to check for an empty string?

    The len() function in Python returns the length of a string, which is zero for an empty string. You can use the len() function to check if a string is empty by comparing its length to zero. Here's an example code snippet:

    my_string = ""
    
    if len(my_string) == 0:
        print("The string is empty.")
    else:
        print("The string is not empty.")

    4. What is the strip() method in Python and how can it be used to check for an empty string?

    The strip() method in Python removes leading and trailing whitespace from a string. You can use the strip() method to check if a string is empty by first stripping it and then checking if its length is zero. Here's an example code snippet:

    my_string = "   "
    
    if len(my_string.strip()) == 0:
        print("The string is empty.")
    else:
        print("The string is not empty.")
    
    
    
    

    You may also like:

    About the author:
    I love writing about Python and have more than 5 years of professional experience in Python development. I like sharing about various standard libraries in Python and other Python Modules.
    Tags:pythonstring
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS