Skip to content

Python check if string is empty | 4 ways Example code

  • by

There are several ways to checks if the string is empty or not in python but the most elegant way would probably be to simply check if it’s true or falsy.

if not my_string:

How to Check If String is Empty or Not in Python example

Check python examples in different ways.

not operator

The not operator in Python checks the string with just spaces to be non-empty.

Note: If the string has the only space, then it will not count as empty, and the not operator returns False.

str1 = ""
if not str1:
    print("Empty String")
else:
    print("Not empty String")

Output:

Python check if string is empty

A len() function

If the len() function returns 0, the string is empty; otherwise, it is not.

Note: If the string contains whitespace, then it does not count as an empty string. Because Space in string counts as a character.

str1 = ""
if len(str1):
    print("Not Empty String")
else:
    print("Empty String")

Output: Empty String

Using not with string.strip()

In the example no matter how many spaces are in the string, it strips all the spaces and checks the length of the string, and if it returns 0, that means the string is empty; otherwise, not.

str1 = "  Hello"
if len(str1):
    print("Not Empty String")
else:
    print("Empty String")

Output: Not Empty String

Using not with string.isspace()

The string isspace() function checks if the string contains any space or not. We use the combination of string and not string.isspace() method to check if the string is empty or not regardless of the space.

str1 = ""
if str1 and not str1.isspace():
    print("Not Empty String")
else:
    print("Empty String")

Output: Empty String

Do comment if you have any doubts and suggestions on this Python string’s latest topic.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading