String data type in Python is immutable; that means you can not change a string once defined. String with spaces is actually an empty string but has non-zero size. So, when you check the empty string with len() or not operator, it counts space as a character in the string, and hence it won’t count a string with space as an empty string.

How to check an empty string in Python

To check an empty string in Python, you can use one of the following methods.

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

Not operator to check empty string

The not operator in Python checks the string with just spaces to be non-empty, which should not practically be True.

## app.py

strA = ""

## checking if string is empty
print("Check if the strA is empty : ", end="")
if(not strA):
    print("The string is empty")
else:
    print("No it is not empty")
Output
Check if the strA is empty : The string is empty

The string is empty, and one thing to note that we did not even put the space in the string. That is why it returns as empty. If we put a space in the string, it will not count as empty, and the not operator returns False.

## app.py

strA = " "

## checking if string with space is empty
print("Check if the strA with space is empty : ", end="")
if(not strA):
    print("The string is empty")
else:
    print("No it is not empty")

#python #programming

How to Check If String is Empty or Not in Python
1.45 GEEK