search

How to check if a string is empty in Python?

To check if a string is empty in Python, you can use a simple condition using the not operator or the len() function. Here are two common approaches:

Using the not operator:

my_string = ""  # Empty string
if not my_string:
    print("The string is empty")
else:
    print("The string is not empty")

In this example, the not operator is used to check if the string my_string is empty. If the string is empty, the condition not my_string evaluates to True, and the message "The string is empty" is printed. If the string is not empty, the condition evaluates to False, and the message "The string is not empty" is printed.

Using the len() function:

my_string = ""  # Empty string
if len(my_string) == 0:
    print("The string is empty")
else:
    print("The string is not empty")

In this example, the len() function is used to get the length of the string my_string. If the length of the string is equal to 0, indicating that there are no characters in the string, the condition len(my_string) == 0 evaluates to True, and the message "The string is empty" is printed. Otherwise, if the length of the string is not equal to 0, the condition evaluates to False, and the message "The string is not empty" is printed.

Both approaches achieve the same result, so you can choose the one that suits your coding style and preference.

Related Questions You Might Be Interested