How to Check If a String Is Empty in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a string is empty in Python. The lab begins by introducing the concept of empty strings, which are strings containing no characters, represented by either single quotes ('') or double quotes (""). You will create and print empty strings using both single and double quotes, verifying their type as str.

The lab then guides you through using the len() function to determine the length of a string and evaluating strings as booleans to check for emptiness. These methods provide practical ways to identify and handle empty strings in your Python code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/variables_data_types("Variables and Data Types") python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/booleans("Booleans") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/variables_data_types -.-> lab-559577{{"How to Check If a String Is Empty in Python"}} python/strings -.-> lab-559577{{"How to Check If a String Is Empty in Python"}} python/booleans -.-> lab-559577{{"How to Check If a String Is Empty in Python"}} python/conditional_statements -.-> lab-559577{{"How to Check If a String Is Empty in Python"}} python/build_in_functions -.-> lab-559577{{"How to Check If a String Is Empty in Python"}} end

Learn About Empty Strings

In this step, you will learn about empty strings in Python. An empty string is simply a string that contains no characters. It is represented by two single quotes ('') or two double quotes (""). Understanding empty strings is crucial because they often serve as initial values for variables or as a way to represent the absence of data.

Let's start by creating an empty string using single quotes:

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named empty_string.py in the ~/project directory.

    ~/project/empty_string.py
  3. Add the following code to the empty_string.py file:

    ## Assign an empty string to a variable
    empty_string = ''
    
    ## Print the empty string
    print(empty_string)
    
    ## Check the type of the variable
    print(type(empty_string))
  4. Save the file.

  5. Open the terminal in VS Code.

  6. Run the script using the python command:

    python empty_string.py

    You should see the following output:

    <class 'str'>

    The first line is empty because we printed an empty string. The second line confirms that the variable empty_string is of type str (string).

Now, let's create an empty string using double quotes:

  1. Modify the empty_string.py file to use double quotes instead of single quotes:

    ## Assign an empty string to a variable
    empty_string = ""
    
    ## Print the empty string
    print(empty_string)
    
    ## Check the type of the variable
    print(type(empty_string))
  2. Save the file.

  3. Run the script again:

    python empty_string.py

    The output will be the same:

    <class 'str'>

    This demonstrates that both single quotes and double quotes can be used to create empty strings in Python.

Empty strings are useful in various scenarios. For example, you might use an empty string to initialize a variable that will later store user input, or to represent a missing value in a dataset. In the following steps, you will learn how to check the length of a string and how empty strings are evaluated as booleans.

Use len() to Check Length

In this step, you will learn how to use the len() function in Python to determine the length of a string. The len() function returns the number of characters in a string. This is a fundamental operation when working with strings, as it allows you to validate input, manipulate text, and perform various other tasks.

Let's start by checking the length of an empty string:

  1. Open the empty_string.py file in the ~/project directory that you created in the previous step.

  2. Modify the code to use the len() function to check the length of the empty string:

    ## Assign an empty string to a variable
    empty_string = ''
    
    ## Check the length of the empty string
    length = len(empty_string)
    
    ## Print the length
    print(length)
  3. Save the file.

  4. Run the script using the python command:

    python empty_string.py

    You should see the following output:

    0

    This confirms that the length of an empty string is 0.

Now, let's check the length of a non-empty string:

  1. Modify the empty_string.py file to assign a non-empty string to the empty_string variable:

    ## Assign a non-empty string to a variable
    empty_string = "Hello, LabEx!"
    
    ## Check the length of the string
    length = len(empty_string)
    
    ## Print the length
    print(length)
  2. Save the file.

  3. Run the script again:

    python empty_string.py

    You should see the following output:

    13

    The length of the string "Hello, LabEx!" is 13, including the space and the exclamation mark.

The len() function can be used with any string, regardless of its content. It is a versatile tool for working with text data in Python. In the next step, you will learn how empty strings are evaluated as booleans in Python.

Evaluate as Boolean

In this step, you will learn how empty strings are evaluated as booleans in Python. In Python, an empty string is considered "falsy," meaning that when used in a boolean context (such as an if statement), it evaluates to False. Non-empty strings, on the other hand, are considered "truthy" and evaluate to True. Understanding this behavior is essential for writing conditional statements that correctly handle string values.

Let's start by testing an empty string in an if statement:

  1. Open the empty_string.py file in the ~/project directory that you created in the previous steps.

  2. Modify the code to include an if statement that checks the boolean value of an empty string:

    ## Assign an empty string to a variable
    empty_string = ''
    
    ## Check if the empty string is truthy or falsy
    if empty_string:
        print("The string is truthy")
    else:
        print("The string is falsy")
  3. Save the file.

  4. Run the script using the python command:

    python empty_string.py

    You should see the following output:

    The string is falsy

    This confirms that an empty string evaluates to False in a boolean context.

Now, let's test a non-empty string in an if statement:

  1. Modify the empty_string.py file to assign a non-empty string to the empty_string variable:

    ## Assign a non-empty string to a variable
    empty_string = "Hello, LabEx!"
    
    ## Check if the non-empty string is truthy or falsy
    if empty_string:
        print("The string is truthy")
    else:
        print("The string is falsy")
  2. Save the file.

  3. Run the script again:

    python empty_string.py

    You should see the following output:

    The string is truthy

    This demonstrates that a non-empty string evaluates to True in a boolean context.

This behavior is useful for checking if a string has been assigned a value or if it contains any meaningful data. You can use this knowledge to write more robust and flexible Python code.

Summary

In this lab, you learned about empty strings in Python, which are strings containing no characters, represented by either single quotes ('') or double quotes (""). You created an empty string using both single and double quotes, assigned it to a variable, and verified its type as str using the type() function.

The lab demonstrated that both single and double quotes are interchangeable for creating empty strings in Python. This understanding is crucial as empty strings are often used to initialize variables or represent the absence of data.