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.
- Using not operator
- Using len() function
- Using not + string.isspace()
- Using len() + string.strip()
- Using and + string.strip()
- 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:
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.