Check if String is Empty or Not – Python
We are given a string and our task is to check whether it is empty or not. For example, if the input is “”, it should return True (indicating it’s empty), and if the input is “hello”, it should return False. Let’s explore different methods of doing it with example:
Using Comparison Operator(==)
The simplest and most commonly used approach is using comparison operator(==):
s = ""
if s == "":
print("The string is empty.")
else:
print("The string is not empty.")
Output
The string is empty.
Explanation: A simple equality check (s == “”) determines if the string is empty.
Using len()
The len() function returns the length of a string so if the length is 0, it means that string is empty:
s = ""
if len(s) == 0:
print("The string is empty.")
else:
print("The string is not empty.")
Output
The string is empty.
Explanation:
- len(s): calculates the length of s.
- If len(s) == 0 then the string is empty.
Using Python’s Truthy/Falsy Behavior
In Python, empty strings are treated as “Falsy”. So, we can use this for checking if a string is empty or not.
s = ""
if not s:
print("The string is empty.")
else:
print("The string is not empty.")
Output
The string is empty.
Explanation: “not s” negates the boolean value of s, if it’s empty then it’s boolean quivalent to False and its negation would be True.