Check if String is Empty or Not in Python

How to check if the Python String is empty or not? In python, there are several ways to check if the string is empty or not. Empty strings are considered as false meaning they are false in a Boolean context. An empty check on a string is a very common and most-used expression in any programming language including python.

Methods to Check if a String is Empty or Not

  1. Since empty strings are False, not operator is used to check if the string is empty or not.
  2. Note that a string with only spaces is not considered empty, hence, you need to strip the spaces before checking for empty.
  3. The bool() function can also be used to check if the string is empty or not.
  4. Operator == is another most used way to check for empty.
  5. The __eq__() is an elegant way to check.
  6. len() function is used to get the length of the string and check if it is 0 to get if a string is empty.
String Empty Check ExpressionResult
if not test_str:True when a string is empty.
False when a string has a value.
if test_str:False when a string is empty.
True when a string has a value.
if test_str.strip():Remove empty spaces and check for empty.
if bool(name):False when a string has a value.
True when a string is empty.
if test_str == "":True when a string is empty.
False when a string has a value.
if "".__eq__(test_str):True when a string is empty.
False when a string has a value.
if len(test_str) == 0:True when a string is empty.
False when a string has a value.
Python String Empty Check Expression Table

1. Quick Examples of Checking if String is Empty

If you are in a hurry, below are some quick examples of how to check whether the given string is empty or not in Python.


# Quick Examples 

# Using not to check if string is empty
print(not "")          # => True
print(not " ")         # => False
print(not " ".strip()) # => True
print(not "test")      # => False
print(not None)        # => True

# Using bool()
print(bool(""))          # => False
print(bool(" "))         # => True
print(bool(" ".strip())) # => False
print(bool("test"))      # => True
print(bool(None))        # => False

# Using == operator
print("" == "")          # => True
print(" " == "")         # => False
print(" ".strip() == "") # => True
print("test" == "")      # => False
print(None == "")        # => False

# Using __eq__()
print("".__eq__(""))         # => True
print("".__eq__(" "))        # => False
print("".__eq__(" ".strip()))# => True
print("".__eq__("test"))     # => False
print("".__eq__(None))       # => NotImplemented

# Using len()
print(len("") == 0)          # => True
print(len(" ") == 0)         # => False
print(len(" ".strip()) == 0) # => True
print(len("test") == 0)      # => False
print(len(None) == 0)        # => Error

2. Check String is Empty using len()

The Python len() is used to get the total number of characters present in the string and check if the length of the string is 0 to identify the string is empty. Actually, the len() function returns the length of an object. The object can be a string, a list, a tuple, or other objects that support the __len__() method.

Let’s create three strings. The first string is empty, the second string is empty but includes spaces and the third is an empty string. I will use these in the example below to check if the string is empty or not.


# Consider the empty string without spaces
first = ""
if(len(first) == 0):
  print("Empty string")
else:
  print("Not empty string")

# Consider the empty string with spaces
second = " "
if(len(second) == 0):
  print("Empty string")
else:
  print("Not empty string")

# Consider the string 
third = "sparkby"
if(len(third) == 0):
  print("Empty string")
else:
  print("Not empty string")

Yields below output.

python check string empty

3. Check String is Empty Using not Operator

The not operator is a logical operator that returns True if the value or expression is False, and False if the value or expression is True. So if we specify not before the string in the if condition, It will become True when the string is empty and False when the string is not empty.


# Consider the empty string without spaces
first=""
if(not first):
  print("Empty string")
else:
  print("Not empty string")

# Consider the empty string with spaces
second="  "
if(not second):
  print("Empty string")
else:
  print("Not empty string")
# Consider the string 
third="sparkby"

if(not third):
  print("Empty string")
else:
  print("Not empty string")

# Output:
# Empty string
# Not empty string
# Not empty string

Explanation:

  1. first string is empty, so it will become False inside if condition. not will convert False to True. Hence statement inside the if condition is executed.
  2. second string is not empty, so it will become True inside if condition. not will convert True to False. Hence statement inside the else block is executed.
  3. last string not empty, so it will become True inside if condition. not will convert True to False. Hence statement inside the else block is executed.

4. Check String is Empty Using bool() Function

The bool() function is a built-in function that returns the Boolean value of a specified object. It returns True if the string is not empty and False if it is empty. Since empty string is considered “falsy” and will evaluate to False when passed to bool(). All other objects are considered “truthy” and will evaluate to True.


# Consider the empty string without spaces
first=""
if(bool(first)):
  print("Not empty string")
else:
  print("Empty string")

# Consider the empty string with spaces
second="  "
if(bool(second)):
  print("Not empty string")
else:
  print("Empty string")

# Consider the string 
third="sparkby"
if(bool(third)):
  print("Not empty string")
else:
  print("Empty string")

# Output:
# Empty string
# Not empty string
# Not empty string

Explanation:

  1. first string is empty, so bool() will return False inside if condition. Hence statement inside the else block is executed.
  2. second string is not empty, so bool() will return True inside if condition. Hence statement inside the if condition is executed.
  3. last string is not empty, so bool() will return True inside if condition. Hence statement inside the if condition is executed.

6. Using == Operator

The == operator is used to test equality between two values. It returns True if the values are equal, and False if they are not. You can use the == operator to compare values of any type, including integers, floats, strings, and objects. In the below example, I am using it with a string variable and comparing it with the empty string "", similarly, you can also use it with string literals to check string equality.


first=""
if "" == first:
   print("Empty string")
else:
   print("Not empty string")

# Output:
# Empty string

7. Using __eq__()

When you use == operator to check if a string is empty or not, it internally uses Python __eq__() function. hence, if you want you can directly use this function.

The __eq__() method is a special method, it is one of the so-called “dunder” methods (short for “double underscore”), which are special methods in Python that have a particular syntax, beginning and ending with two underscores.


# Using __eq__()
first=""
if ""__.eq__(first):
   print("Empty string")
else:
   print("Not empty string")

# Output:
# Empty string

8. Using list Comprehension to Check String is Empty

Finally, let’s use the python list comprehension to check if the string is empty or not.


# Using list comprehension
first=""
x=["Not empty string" if len(first)>0 else "Empty string"]
print(x)

# Output:
# Empty string

Frequently Asked Questions On Check if String is Empty or Not

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

You can use the if not my_string: syntax to check if a string is empty. This evaluates to True if the string is empty.

Are there other ways to check for an empty string?

There are additional ways to check for an empty string in Python. You can use the len() function or the strip() method.

Why use if not my_string: instead of if my_string == “”?

Using if not my_string: is generally preferred over if my_string == "" for a few reasons:
Conciseness: The if not my_string: syntax is more concise and reads naturally. Pythonic code often emphasizes readability and brevity.
Implicit Boolean Evaluation: In Python, empty strings, empty lists, and similar objects are considered “falsy” in a boolean context. Using if not my_string: implicitly checks if the string is empty or evaluates to False. It’s a more idiomatic way to check for emptiness.
Versatility: The if not my_string: approach works not only for empty strings but also for any falsy values. For example, it will also catch None, False, or 0.
Performance: The if not my_string: approach can be more efficient because it avoids an explicit comparison (==) and directly leverages the truthy/falsy nature of values in Python.

Can a string be both empty and have whitespace characters?

A string can be non-empty but contain only whitespace characters. To handle this, you might want to use if not my_string.strip() to check for the presence of non-whitespace characters.

How does strip() work in checking for an empty string?

The strip() method removes leading and trailing whitespaces from a string. If the resulting string is empty, it means the original string was either empty or contained only whitespaces.

Conclusion

In this article, you have learned different ways to check if the string is empty or not in Python. Since empty strings are considered as false in Python, we can directly use it on the if condition to check or use it with either not operator or bool() function. And also learned to use the == operator and __eq__() to check whether strings are empty or not.

Leave a Reply

You are currently viewing Check if String is Empty or Not in Python