How to check if a string is empty in Python [8 methods]

In this Python tutorial, I will explain how to check if a string is empty in Python using various methods with illustrative examples.

An empty string in Python refers to a string that contains no characters. It’s represented by two quotation marks (either single or double) with nothing in between them. For example, both “” and represent empty strings.

Sometimes an empty string can be defined by the user as like, a string with only whitespace, etc.

Methods to check if a string is empty in Python

There are eight different ways to check if a string is empty in Python

  • The not operator
  • The == operator
  • The len operator
  • The + operator
  • The not and strip() function
  • The not and isspace()
  • List comprehension
  • The Bool function

Let’s see them one by one with demonstrative examples:

Method 1: To check if a string is empty in Python use the not operator

An empty string in Python is falsy, which means it evaluates to False in a boolean context. So, we can use the not operator to check if a string is empty.

For instance, Suppose we’re building a web application through Python for booking tickets to various US monuments. A user enters the monument’s name they want to visit. We want to check if they’ve entered a name or left it blank.

monument_name = input("Enter the name of the monument: ")
if not monument_name:
    print("You didn't enter a monument name!")
else:
    print(f"Booking ticket for {monument_name}.")

Output: We didn’t give any input, it will be treated as an empty string in Python.

Enter the name of the monument: 
You didn't enter a monument name!
python check if string is empty

This way we can use the ‘not’ operator to check if the string is empty or not in Python.

Method 2: Check if String is Empty or Not in Python using the == operator

We can directly compare the Python string with an empty string (“” or ”) to check if it’s empty.

For example, Imagine we’re at a polling booth in the US, and people enter their choice of candidate. If someone doesn’t enter a name, we want to prompt them again through Python.

candidate_name = input("Enter the candidate's name you're voting for: ")
if candidate_name == "":
    print("You didn't enter a candidate's name!")
else:
    print(f"You voted for {candidate_name}.")

Output: We didn’t give any input, it will be treated as an empty string in Python.

Enter the candidate's name you're voting for: 
You didn't enter a candidate's name!
Check if String is Empty or Not in Python

This way, we can use the == operator to Python check for empty string.

Method 3: Checking if Python string is empty or not using the len() function

The len() function gives the length of a string. The length of an empty Python string is 0. Using the built-in len() function in Python on an empty string will return 0.

For instance, Let’s say we’re signing up for an online course on American history. When entering the title of our favorite historical event, the Python system checks if we’ve provided input.

event_title = input("Enter the title of your favorite historical event: ")
if len(event_title) == 0:
    print("You didn't provide an event title!")
else:
    print(f"Your favorite historical event is {event_title}.")

Output: We didn’t give any input, it will be treated as an empty string in Python.

Enter the title of your favorite historical event: 
You didn't provide an event title!
How to check if the string is empty in Python

This way we can use the == operator to check whether the string in Python is empty or not.

Method 4: Python Program to Check if String is Empty or Not using the + operator

The + operator is primarily used for string concatenation in Python. However, with some creativity, it can be used indirectly to check if a string is empty in Python. Here’s a way to do it:

The idea is to concatenate the Python string in question with another known non-empty string and then check if the result is equal to the non-empty string. If the result is the same as the non-empty string, then the original string is empty in Python.

For instance, Imagine we’re working on an application for a popular U.S. fast-food chain. Users can enter promotional codes to get discounts. We want to check if the user has entered a code or just left it blank before verifying the validity of the code through Python.

def is_empty_using_plus(promo_code):
    known_non_empty_string = "USA"
    return (promo_code + known_non_empty_string) == known_non_empty_string

promo_code_from_user = input("Enter your promotional code for a USA fast-food discount: ")

if is_empty_using_plus(promo_code_from_user):
    print("You didn't enter any promotional code! Please provide a valid code for discounts.")
else:
    print(f"Checking validity of the promo code: {promo_code_from_user}")

Output: We didn’t give any input, it will be treated as an empty string in Python.

Enter your promotional code for a USA fast-food discount: 
You didn't enter any promotional code! Please provide a valid code for discounts.
Python Program to Check if String is Empty or Not

This way we can use the + operator to check if Python string is empty.

Method 5: Check in if a Python string is empty using the not and strip() function

Sometimes, users might enter spaces, thinking they’ve provided valid input through Python. The strip() method in Python can be used to remove spaces at the beginning and end of a Python string. If the result is an empty string, it means the original string had only spaces.

For example, Suppose we’re conducting a survey in a US city about favorite local cuisines. If someone just enters spaces, we’ll prompt them to enter a valid cuisine name through Python.

cuisine_name = input("Enter your favorite local cuisine: ")
if not cuisine_name.strip():
    print("Please enter a valid cuisine name!")
else:
    print(f"Your favorite cuisine is {cuisine_name}.")

Output:

Enter your favorite local cuisine:       
Please enter a valid cuisine name!
Python Program to Check if String is Empty

This way we can use the not operator with strip() method to check if a string in Python is empty.

Method 6: Check if an empty string is present in Python using the not operator and isspace() method

This method returns True if the Python string consists of only whitespace characters and is not empty. This can be a quick way to check for Python strings with only spaces.

Scenario: Imagine we’re collecting feedback for a new American TV series. If a viewer only enters spaces for the series title, we’ll remind them to enter the correct title through a message in Python.

series_title = input("Enter the title of the TV series: ")
if series_title.isspace():
    print("Please enter a valid series title!")
else:
    print(f"You provided feedback for {series_title}.")

Output:

Enter the title of the TV series:     
Please enter a valid series title!
how to check if a string is empty in Python

This way we can check if a string in Python is empty using the not operator and isspace() method.

Method 7: Check if a Python string is empty using list comprehension

List comprehension creates a list in Python of non-space characters from the string. If the resultant Python list is empty, the string was either empty or consisted only of spaces.

Scenario: We’re collecting names of American national parks and want to ensure no entry is just spaces through Python.

park = "   "
if not [char for char in park if not char.isspace()]:
    print("Park entry is empty or only spaces!")

Output:

Park entry is empty or only spaces!
Python string is empty check

This way we can use list comprehension to check if the Python string is empty.

Method 8: Check if the Python string is empty using bool

The bool() directly converts the string to a boolean. Empty strings are evaluated as False.

Scenario: For a cultural event, organizers are collecting data on favorite American dishes through Python. Not all participants might give a valid entry.

dish = ""
if not bool(dish):
    print("Dish entry is empty!")

Output:

Dish entry is empty!
python check in if a string is empty

This way we use the bool() function to check if a string in Python is empty.

Conclusion

This tutorial explains how to check if a string is empty in Python using eight different methods such as not operator, == operator, len() function, + operator, strip() function, isspace() function, List comprehension, and the bool() function with illustrative examples.

These methods offer various ways to determine if a Python string is empty or contains only whitespace, depending on the specific use case and requirements.

You may also like to read: