How to check if the string is empty?
To check if a string is empty in Python, you can use the len() function or an if statement.
To check if a string is empty in Python, you can use the len() function or an if statement.
Here are two examples:
Example 1: Using len() function
Check if a string is empty using len function in Python
string = ""
if len(string) == 0:
print("The string is empty.")
else:
print("The string is not empty.")
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Example 2: Using an if statement
Check if a string is empty using type coercion in Python
string = ""
if string:
print("The string is not empty.")
else:
print("The string is empty.")In both examples, the output will be "The string is empty.".
You can also use the bool() function to check if the string is empty. An empty string is considered False in a boolean context, so you can do something like this:
Convert a string to boolean in order to check if a string is empty in Python
string = ""
if bool(string):
print("The string is not empty.")
else:
print("The string is empty.")