How do I check if a string is empty in Python?
Alex K
alex k profile pic

In Python, you can check if a string is empty using various approaches. Here's a detailed explanation of a few commonly used methods: Using the len() function: You can check if a string is empty by comparing its length to zero using thelen() function.

1
2
3
4
5
6
7

my_string = ""

if len(my_string) == 0:
    print("String is empty.")
else:
    print("String is not empty.")

In this example,len(my_string) == 0 checks if the length of the stringmy_string is equal to zero. If it is, the string is considered empty, and the corresponding message is printed. Using the not operator: You can use thenot operator to check if a string is empty by treating it as a Boolean value.

1
2
3
4
5
6
7

my_string = ""

if not my_string:
    print("String is empty.")
else:
    print("String is not empty.")

In this example,not my_string checks if the stringmy_string evaluates toFalse. An empty string is consideredFalse in a Boolean context, so the condition is satisfied, and the message "String is empty" is printed. Using comparison to an empty string: You can directly compare the string to an empty string using the equality operator==.

1
2
3
4
5
6
7

my_string = ""

if my_string == "":
    print("String is empty.")
else:
    print("String is not empty.")

In this example,my_string == "" compares the stringmy_string to an empty string. If they are equal, the string is considered empty, and the corresponding message is printed. Using string.strip(): You can use thestrip() method to remove leading and trailing whitespace characters from the string, and then check if the resulting string is empty.

1
2
3
4
5
6
7

my_string = "   "

if my_string.strip() == "":
    print("String is empty.")
else:
    print("String is not empty.")

In this example,my_string.strip() removes any leading and trailing whitespace characters frommy_string, resulting in an empty string. The conditionmy_string.strip() == "" checks if the stripped string is empty, and the appropriate message is printed. It's important to note that all of these methods consider a string empty if it has no characters. If the string contains whitespace characters, such as spaces or tabs, it is still considered non-empty. Choose the method that best suits your needs based on the specific requirements of your program.