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.

Here are two examples:

Example 1: Using len() function

string = ""
if len(string) == 0:
    print("The string is empty.")
else:
    print("The string is not empty.")

Watch a course Python - The Practical Guide

Example 2: Using an if statement

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:

string = ""
if bool(string):
    print("The string is not empty.")
else:
    print("The string is empty.")