How to check if a string is empty in Python
How to check if a string is empty in Python.
Here is a step-by-step tutorial on how to check if a string is empty in Python.
Step 1: Understanding an empty string
In Python, an empty string is a string that doesn't contain any characters. It is represented by two quotation marks with no characters in between, like this: ""
.
Step 2: Using the len() function
The len()
function in Python returns the length of a string, which is the number of characters it contains. To check if a string is empty, we can use the len()
function and compare its result to zero.
Here is an example:
string1 = ""
if len(string1) == 0:
print("The string is empty.")
else:
print("The string is not empty.")
Output:
The string is empty.
In this example, we create a string string1
that is empty. We pass string1
to the len()
function, and if the length is equal to zero, we print "The string is empty." Otherwise, we print "The string is not empty."
Step 3: Using a comparison operator
Instead of comparing the result of len()
to zero, we can use a comparison operator directly to check if the string is empty.
Here is an example:
string2 = ""
if string2 == "":
print("The string is empty.")
else:
print("The string is not empty.")
Output:
The string is empty.
In this example, we compare string2
directly to an empty string ""
. If the comparison is true, we print "The string is empty." Otherwise, we print "The string is not empty."
Step 4: Using the not operator
We can also use the not
operator to check if a string is empty. By using not
before a string, it will return True
if the string is empty, and False
otherwise.
Here is an example:
string3 = ""
if not string3:
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 before string3
. If string3
is empty, the not
operator will return True
, and we print "The string is empty." Otherwise, we print "The string is not empty."
Conclusion
You have learned different ways to check if a string is empty in Python. You can use the len()
function, comparison operators, or the not
operator to determine if a string contains any characters or not.