In your Python journey you will come across a scenario where you will need to test if a given Python string is empty. For instance, you could be getting input from a user (e.g., asking the user for his or her name) and want to check for an empty input (i.e., the user just pressing Enter without typing anything). Let us see how to check if a Python string is empty!
There are three ways to check if a Python string is empty. First, you can check for equality to the empty string. Second, you can use the len() function and see if it returns a zero. Finally, you can evaluate the string in a conditional context and use the fact that empty strings will evaluate to false.
Method 1: Check for equality to the empty string
Here is a simple program that checks for an empty string by testing for equality to the empty string:
In the program above, we first obtain input from the user and store it in the variable called “name”. Then we check if “name” is empty by comparing it to “”. If it is empty, we print a useful message. Else, we create a greeting message.
Here is a sample run where we just press the Enter key when prompted (thus making “name” to be an empty string):
Let us try entering a name when prompted:
Note that for your input to be counted as an empty string, you need to press just Enter. Pressing a space key for instance does not constitute an empty string. Here is what happens when we do that:
It prints a “Hi” with a space and an exclamation point.
Method 2: Use the len() function to check for an empty string
The second way to check if a string is empty is to apply the len() function on the string. If the length is zero, then it is an empty string.
Let us modify our program above to use len():
This program works exactly the same as the previous program. Here are three separate runs to illustrate the idea:
Method 3: Evaluate the string in a conditional context
The third approach to check if a string is empty is to evaluate it in a conditional context. An empty string will always evaluate to False. Any non-empty string will evaluate to True. With this observation, we modify our program as:
Here, we are checking if name is empty by evaluating “not name” inside the if clause. If the string is empty, then “name” will evaluate to False, so that (not name) will evaluate to True and thus the message that the string is empty will be printed.
Here are three runs of our program as before:
We have seen three different ways to check if a string is empty in Python. Which is your favorite?
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.