How to Check If a String is Empty in Python
To check if a string is empty in Python, you can use the len() function, an if statement, or the not operator with the bool() function.
The following examples show how to check if a string is empty in Python.
Using len() Function
We can use the len() function to check if a string is empty.
Suppose we have the following string:
# Declare string
name = ""
# Check if the string is empty
if len(name) == 0:
print("The string is empty.")
else:
print("The string is not empty.")
Output: 👇️
The string is empty.
In this example, we use the len() function to check if the length of name is 0, indicating that the string is empty.
Using if Statement
We can use an if statement to check if a string is empty.
Suppose we have the following string:
# Declare string
name = "Anita"
# Check if the string is empty
if not name:
print("The string is empty.")
else:
print("The string is not empty.")
Output: 👇️
The string is not empty.
In this example, we use an if statement to check if name is empty. The condition if not name evaluates to True if the string is empty.
Using not Operator & bool() Function
We can use the not operator with the bool() function to check if a string is empty.
Suppose we have the following string:
# Declare string
name = ""
# Check if the string is empty
if not bool(name):
print("The string is empty.")
else:
print("The string is not empty.")
Output: 👇️
The string is empty.
In this example, we use the not operator with the bool() function to check if name is empty. The condition if not bool(name) evaluates to True if the string is empty.
Conclusion
We can use the len() function, an if statement, and the not operator with the bool() function to check if a string is empty in Python.