Skip to content

Python check if string is not empty

  • by

Use Python’s len() function to determine the length of the string. Then, if the length of the string does not equal 0, the string is not empty.

In Python, we can use one of the basic ways described below to check for an empty string.

  1. Using not operator
  2. Using len() function
  3. Using not + string.isspace()
  4. Using len() + string.strip()
  5. Using and + string.strip()
  6. Using __eq__

Python checks if a string is not empty

Simple example code.

s1 = ""
s2 = "   "
print(not s1)
print(not s2)

length1 = len(s1)
length2 = len(s2)

if length1 == 0:
    print("s1 is empty")
else:
    print("s1 not empty")

if length2 == 0:
    print("s2 is empty")
else:
    print("s2 is not empty")

Output:

Python checks if a string is not empty

Do comment if you have any doubts or suggestions on this Python string 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

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