Tutorial

How to Handle or Check if String is empty in Python

6 min read

In this tutorial, we will delve into several ways we can check whether a string is empty or not. We’ll explore these methods by providing Python code examples.

Also, we will explain to help you choose the most appropriate approach based on the requirements of your specific use case.

So, let’s begin.

Introduction to check if a string is empty using Python

In Python, managing strings is a fundamental aspect of various applications, ranging from user interactions and data processing to file handling.

An essential consideration in this context is the effective handling and checking of empty strings. There are strings with no characters.

Empty strings can be encountered in user inputs, data retrieved from external sources, or during various string manipulation operations.

Handling empty strings is crucial to ensuring the correctness and reliability of your Python programs.

Whether you’re working with user inputs, data processing, or file handling, it’s essential to identify and manage empty strings appropriately.

Why do you need to check if a string is empty?

Let’s consider a scenario where we have a CSV file containing housing data.

One of the fields, the "price" field has some empty strings. We’ll attempt to read and process this CSV data without explicitly handling the empty strings:

import csv

# Read CSV data from the file
with open('housing.csv', 'r') as csv_file:
    # Use DictReader to read the CSV file into a list of dictionaries
    csv_rows = list(csv.DictReader(csv_file))

# Create a list of prices. We will get error here because 
# of the empty strings
prices = [float(row['price']) for row in csv_rows]

In this example, we attempt to create a list of prices. Within the list comprehension, we try to convert each of the price data into a float.

Further, we attempt the conversion without explicitly checking for empty strings.

This oversight led to the ValueError exception:

output ValueError when converting empty string to float

This demonstrates the importance of handling empty strings, especially when dealing with external data sources like CSV files.

Here are a few ways to check if String is empty in Python

Now, we want to learn different ways to check if a string is empty in Python programming.

The methods we will cover are:

  1. Directly comparing with an empty string
  2. Checking for Falsiness
  3. Checking the length of the string

Depending on the use case, we can decide which one best suits our code.

Check if a string is empty by comparing it with an empty string

One of the most straightforward ways to check if a string is empty is by directly comparing it with an empty string using the equality (==) operator.

Here is a Python program to check if a string is empty or not

my_string = "Hello, World!"

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

In this example code above, the program checks whether the variable my_string is equal to an empty string.

If the condition is true, it prints a message indicating that the string is empty.

The output we get here is as follows-output string is not empty
The direct comparison approach is easy to understand and implement.

It’s a simple and easy way to check for emptiness. The code communicates the intention of checking for an empty string.

Check for Falsiness to verify if String is Empty in Python

An alternative way to direct comparison is the use of the not operator to check for an empty string.

Python code example to check if string is empty

my_string = ""

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

In this code snippet, the program evaluates the truthiness of my_string using the not operator.

If the string is empty or evaluates to False, it prints a message indicating that the string is empty.

Otherwise, it means that the string is not empty.

In this case, we get the output as below-
output string is empty

This method is also succinct, and versatile as it can also be applied to any value in Python to determine its falsiness.

Check empty string by Checking zero string length

Here is one more way to check empty strings in Python by inspecting the length of the string.

Let’s delve into this technique with a concise Python code example:

my_string = ""

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

The check for emptiness we use the character count.

An empty string has zero characters. Therefore, the program verifies if the length of my_string is zero.

If true, it concludes that the string is empty and prints a corresponding message.

In this case, our program prints the message:

output string is empty

Checking the length explicitly communicates the criterion for emptiness: a string with zero characters.

This approach is not limited to empty strings; it can be adapted for length-based conditions, such as checking for strings of a specific length.

How to  Handle empty strings in CSV data using Python?

Imagine you have a CSV file named "housing.csv" containing housing data, and some rows have empty strings in the price field.

The goal is not just to replace empty strings with a fixed value but to enhance the data integrity by filling them with the median of existing numeric values.

Let’s break down the Python code that accomplishes this task:

import csv
import statistics

# Read CSV data from housing.csv into a list of dictionaries
csv_rows = list(csv.DictReader(open('housing.csv', 'r')))

# Extract non-empty numeric values from the "price"
numeric_values = [float(row['price']) for row in csv_rows if row['price']]

# Calculate the median of existing prices
median_price = statistics.median(numeric_values)

# Identify indices with empty strings in the "price" field
empty_strings = [index for index, row in enumerate(csv_rows) if not row['price']]

# Handle empty strings by replacing them with the median in the "price" field
for index in empty_strings:
    csv_rows[index]['price'] = str(median_price)

# Print the modified CSV data
for row in csv_rows:
    print(row)

# Save the modified data back to the CSV file
with open('housing_modified.csv', 'w', newline='') as csv_file:
    fieldnames = csv_rows[0].keys()
    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)

    # Write the header
    writer.writeheader()

    # Write the modified rows
    for row in csv_rows:
        writer.writerow(row)

print("Modified data saved to housing_modified.csv")

After executing our code, we get the output:

output modified housing data

The code example makes use of the statistics.median function to calculate the median of the price field.

Instead of a fixed value, we replace empty strings with the calculated median.

This enhances the data by providing a more representative and context-aware fill. The modified data is saved to a new CSV file named "housing_modified.csv" to preserve the original data.

Conclusion

In conclusion, effectively handling and checking empty strings is crucial in various Python applications.

Whether it’s user input validation or data processing tasks, choosing the right method ensures robust and reliable code.

Consider the specific requirements of your project when implementing these techniques.

If you enjoy our articles, please feel free to check out our Python tutorials which can show you how to solve Python-related coding problems. Also, if you want a private Python tutor then you can contact us directly.