Recently in a Python webinar, someone asked me how to check if a string is empty or NaN in Python. After researching, I found some important methods, in this tutorial, I will explain how to check if a string is empty and if a string is NaN in Python separately with examples that will help you to understand better.
Empty Strings
An empty string is a string that contains no characters. In Python, an empty string is represented by a pair of quotation marks with nothing in between, like this: "" or ''. Empty strings are often used to initialize variables or to represent the absence of a value.
NaN Values
NaN, which stands for “Not a Number,” is a special floating-point value that represents an undefined or unrepresentable value. In Python, NaN is part of the float data type and can be encountered when performing mathematical operations that don’t have a well-defined result, such as dividing by zero or taking the square root of a negative number.
Check for Empty Strings in Python
Python provides several ways to check if a string is empty. Let’s explore a few common approaches.
Read Access Modifiers in Python
Method 1. Use the len() Function
The len() function returns the length of a string. If the length is zero, it means the string is empty. Here’s an example:
name = ""
if len(name) == 0:
print("The string is empty.")
else:
print("The string is not empty.")Output:
The string is empty.I have executed the above example code and added the screenshot below.

In this example, we have a variable name that holds an empty string. We use the len() function to check its length. If the length is equal to zero, we print “The string is empty.” Otherwise, we print “The string is not empty.”
Check out Interfaces in Python
Method 2. Use the not Operator
In Python, empty strings are considered falsy, meaning they are evaluated False in a boolean context. We can leverage this behavior and use the not operator to check if a string is empty. Here’s an example:
city = ""
if not city:
print("The string is empty.")
else:
print("The string is not empty.")Output:
The string is empty.I have executed the above example code and added the screenshot below.

In this case, if the city variable is an empty string, the condition not city will evaluate to True, and the code inside the if block will be executed.
Check out Python 3 vs Python 2
Compare with an Empty String
Another simple approach is to directly compare the string with an empty string using the equality operator (==). Here’s an example:
state = ""
if state == "":
print("The string is empty.")
else:
print("The string is not empty.")Output:
The string is empty.I have executed the above example code and added the screenshot below.

If the state variable is an empty string, the condition state == "" will evaluate to True, and the code inside the if block will be executed.
Read Difference Between “is None” and “== None” in Python
Check for NaN Values
When working with numerical data, it’s common to encounter NaN values. Python provides several ways to check if a value is NaN.
Method 1. Use the math.isnan() Function
The math module in Python provides the isnan() function, which returns True if the given value is NaN and False otherwise. Here’s an example:
import math
salary = float("nan")
if math.isnan(salary):
print("The value is NaN.")
else:
print("The value is not NaN.")Output:
The value is NaN.I have executed the above example code and added the screenshot below.

In this example, we have a variable salary that holds a NaN value. We use the math.isnan() function to check if salary is NaN. If it is, we print “The value is NaN.” Otherwise, we print “The value is not NaN.”
Check out How to Comment Out a Block of Code in Python?
Method 2. Use the numpy.isnan() Function
If you’re working with NumPy arrays, you can use the numpy.isnan() function to check for NaN values. Here’s an example:
import numpy as np
ages = np.array([25, 30, np.nan, 40])
if np.isnan(ages).any():
print("The array contains NaN values.")
else:
print("The array does not contain NaN values.")In this case, we have a NumPy array ages that contains a NaN value. We use np.isnan() to create a boolean mask that indicates which elements are NaN. Then, we use the any() function to check if any element in the mask is True. If it is, we print “The array contains NaN values.” Otherwise, we print “The array does not contain NaN values.”
Read Difference Between {} and [] in Python
Method 3. Use the pandas.isnull() Function
If you’re working with pandas DataFrames, you can use the pandas.isnull() function to check for NaN values. Here’s an example:
import pandas as pd
data = pd.DataFrame({'Name': ['John', 'Emily', 'Michael', 'Jessica'],
'Age': [28, pd.np.nan, 35, 29]})
if data['Age'].isnull().any():
print("The 'Age' column contains NaN values.")
else:
print("The 'Age' column does not contain NaN values.")In this example, we have a pandas DataFrame data with a column ‘Age’ that contains a NaN value. We use data['Age'].isnull() to create a boolean mask indicating which elements in the ‘Age’ column are NaN. Then, we use the any() function to check if any element in the mask is True. If it is, we print “The ‘Age’ column contains NaN values.” Otherwise, we print “The ‘Age’ column does not contain NaN values.”
Check out Is Python an Object-Oriented Language?
Handle Empty Strings and NaN Values
Now that we know how to check for empty strings and NaN values, let’s discuss some strategies for handling them in your code.
1. Provide Default Values
If you encounter an empty string or a NaN value, you can choose to provide a default value instead. This can be useful when you need to ensure that your code continues executing without errors. Here’s an example:
address = ""
default_address = "123 Main St, Anytown, USA"
if not address:
address = default_address
print("Address:", address)In this case, if the address variable is an empty string, we assign it the value of default_address. This way, we ensure that address always holds a non-empty string value.
Read Difference Between is and == in Python
2. Filter Out Empty Strings and NaN Values
Another approach is to filter out empty strings and NaN values from your data before processing it further. This can help you work with clean and valid data. Here’s an example:
names = ["John", "", "Emily", "Michael", "", "Jessica"]
filtered_names = [name for name in names if name]
print("Filtered Names:", filtered_names)In this example, we have a list names that contains some empty strings. We use list comprehension to create a new list filtered_names that includes only the non-empty names. The condition if name filters out empty strings.
Check out How to Comment Out Multiple Lines in Python?
Conclusion
In this tutorial, we explored various methods to check if a string is empty or NaN in Python. We discussed checking for empty strings using the len() function, the not operator, and comparing with an empty string. We also covered checking for NaN values using the math.isnan() function, the numpy.isnan() function, and the pandas.isnull() function. we also covered how to handle empty strings and NaN values.
You may also like to read:
- Python input() vs raw_input()
- PyCharm vs. VS Code for Python
- How to Create a Void Function in Python?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.