Contents
Python – Check if string is empty
To check if given string is empty, you can either use the string variable as is inplace of a condition along with not operator, or verify if the string equals empty string "" using equal to operator.
In this tutorial, we will write example programs for each of the processes mentioned above.
Examples
1. Check if given string is empty using if-else
In this example, we will take an empty string, and verify if this string is empty or not programmatically, by placing the string in place of condition in an If conditional statement.
If the string is empty, the string represents false value. So, if we use not operator with the string, we will get true if the string is empty, and false if the string is not empty.
Python Program
mystring = ""
if not mystring:
print("The string is empty.")
else:
print("The string is not empty.")
Run Code CopyOutput
The string is empty.
2. Check if given string is empty using Equal-to Operator
In this example, we will take an empty string, and verify if this string is empty or not programmatically using equal to operator.
The syntax for condition to check if the given string equals empty string is
mystring == ""
We will use this condition in an If statement.
Python Program
mystring = ""
if mystring == "":
print("The string is empty.")
else:
print("The string is not empty.")
Run Code CopyOutput
The string is empty.
Summary
In this tutorial of Python Examples, we learned how to check if a given string is empty or not.