Python Program to Check if String is Empty or Not
Last Updated :
18 Nov, 2024
Improve
In this article, we will explore various methods to check if string is empty or not. The simplest and most commonly used approach is using comparison operator(==).
Using Comparison Operator(==)
s = ""
# Check if the string is empty
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.
Let’s explore other different method to check if string is empty or not:
Table of Content
Using len()
The len() function returns the length of a string. If the length is 0 means string is empty.
s = ""
# Using len() to check if the string is empty
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 = ""
# Check using truthy/falsy behavior
if not s:
print("The string is empty.")
else:
print("The string is not empty.")
Output
The string is empty.