Skip to content

How to check if text is “empty” (spaces, tabs, newlines) in Python?

  • by

To check if a text string is “empty” (contains only spaces, tabs, or newlines) in Python, you can use the isspace() method available on string objects. Here’s a simple function to check if the text is empty:

string.isspace()
  • string: This is the string on which you want to perform the check.
  • isspace(): This is the method itself. When called on a string, it returns True if all characters in the string are whitespace characters (spaces, tabs, and newlines), and False otherwise.

Let’s see an example of how to use the isspace() method:

text1 = "   \t\n"  # Only contains spaces, tabs, and newlines
text2 = "Hello, world!"  # Contains non-whitespace characters

print(text1.isspace())  # Output: True
print(text2.isspace())  # Output: False

The isspace() method returns True if all characters in the string are whitespace characters (spaces, tabs, or newlines), and False otherwise.

Check if the text is “empty” (spaces, tabs, newlines) in Python

Here’s an example of how to check if a text string is empty (contains only spaces, tabs, or newlines) in Python:

def is_text_empty(text):
    # Remove all spaces, tabs, and newlines from the text
    stripped_text = text.replace(" ", "").replace("\t", "").replace("\n", "")
    
    # Check if the stripped text is empty
    return not stripped_text

# Test cases
text1 = "   \t\n"  # Only contains spaces, tabs, and newlines
text2 = "Hello, world!"  # Contains non-whitespace characters

print(is_text_empty(text1))  # Output: True
print(is_text_empty(text2))  # Output: False

Output:

How to check if text is “empty” (spaces, tabs, newlines) in Python?

In this example, the is_text_empty() function takes a text string as input, and it first removes all spaces, tabs, and newlines using the replace() method. After that, it checks if the resulting stripped text is empty (has a length of 0) using the not operator, and returns True if it’s empty, and False otherwise.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *