I find hardcoding[sic] "" every time for checking an empty string not as good.
Clean code approach
Doing this: foo == ""
is very bad practice. ""
is a magical value. You should never check against magical values [more commonly known as magical numbers]
What you should do is compare to a descriptive variable name.
Descriptive variable names
One may think that "empty_string" is a descriptive variable name. It isn't.
Before you go and do empty_string = ""
and think you have a great variable name to compare to. This is not what "descriptive variable name" means.
A good descriptive variable name is based on its context. You have to think about what the empty string is.
- Where does it come from.
- Why is it there.
- Why do you need to check for it.
Simple form field example
You are building a form where a user can enter values. You want to check if the user wrote something or not.
A good variable name may be not_filled_in
This makes the code very readable
if formfields.name == not_filled_in:
raise ValueError["We need your name"]
Thorough CSV parsing example
You are parsing CSV files and want the empty string to be parsed as None
[Since CSV is entirely text based, it cannot represent None
without using predefined keywords]
A good variable name may be
CSV_NONE
This makes the code easy to change and adapt if you have a new CSV file that represents None
with another string than ""
if csvfield == CSV_NONE:
csvfield = None
There are no questions about if this piece of code is correct. It is pretty clear that it does what it should do.
Compare this to
if csvfield == EMPTY_STRING:
csvfield = None
The first question here is, Why does the empty string deserve special treatment?
This would tell future coders that an empty string should always be considered as None
.
This is
because it mixes business logic [What CSV value should be None
] with code implementation [What are we actually comparing to]
There needs to be a separation of concern between the two.
In this tutorial, you’ll learn how to use Python to check if a string is empty or not. Being able to work with strings and see whether or not they are empty is an important skill to learn. Python strings are immutable, meaning that they cannot be changed once they’re created. Because of this, it can be useful to check if a string is empty or not.
By the end of this tutorial, you’ll have learned:
- What is considered an empty string in Python
- How to use the
not
keyword to check if a string is empty - How to check if a string is empty based on its length
- How to Create an Empty String in Python
- Use not To Check if a String is Empty in Python
- Use len to Check if a String in Empty in Python
- Use strip to Check if a String is Blank in Python
- Conclusion
- Additional Resources
In Python, you can create an empty string in a number of ways. The simplest, and clearest, way is simply to create a string with nothing in it. This can be done using either single, double, or triple quotes. Let’s see what this looks like:
# Creating an Empty String in Python
empty1 = ''
empty2 = ""
empty3 = """"""
Similarly, we can use the string constructor function str[]
to create an empty string in Python. Let’s see what this looks like and print it out:
# Creating an Empty String in Python
empty = str[]
print[empty]
# Returns
#
Are Strings of Spaces Considered Empty in Python?
In the examples above, the strings were truly empty. Now, take a string like this for example:
# Is this empty?
empty = ' '
Would we consider this empty? Well, it depends. From a technical perspective, the string isn’t empty. From a practical perspective, the string is empty. To get semantics out of the way, let’s consider a string that’s made up entirely of spaces or whitespace to be “blank”.
Use not To Check if a String is Empty in Python
The simplest, and most Pythonic, way of checking if a string is empty in Python is to simply use an if-else block with the not
keyword. Empty strings in Python are considered to be falsy, meaning that they evaluate to False
.
Because of this, we can easily check if a string is empty by checking its boolean truth:
# Checking if a String is Empty in Python
string = ''
print[not string]
# Returns: True
What this expression evaluates to is not False
, which then evaluates to True
.
A cleaner, and more
practical way to write this, is using an if-else
block. With this we can run an expression when a string is empty or not:
# Checking if a String is Empty with an if-else
string = ''
if not string:
print["Empty string!"]
else:
print["Not empty string!"]
# Returns:
# Empty string!
In the next section, you’ll learn how to check if a string is empty using the len[]
function.
Use len to Check if a String in Empty in Python
Because empty strings in Python are, well, empty, you can also check the length of a string to see if it’s empty or not. This
is done using the len[]
function, which returns the length of an iterable object passed into it.
Let’s see how we can use this function to check if a string is empty or not:
# Using len[] To Check if a String is Empty
string = ''
if len[string] == 0:
print["Empty string!"]
else:
print["Not empty string!"]
# Returns
# Empty string!
Keep in mind that this only checks if a string is truly empty. In the following section, you’ll learn how to check if a string is either empty or blank.
Use strip to Check if a String is Blank in Python
In
this section, you’ll learn how to check if a string is both empty as well as blank, meaning that it only contains whitespace. In order to do this, we first need to apply the .strip[]
method to the string, which returns a string without any whitespace. We can then use either not
keyword or the len[]
function to check if it’s empty.
Let’s see what this looks like. We’ll create a string that contains a few spaces and combine the .strip[]
method with the not
keyword:
# Checking if a String is Blank in Python
string = ' '
if not string.strip[]:
print["Blank string!"]
else:
print["Not blank string!"]
# Returns
# Blank string!
Note that because strings in Python are immutable, the original string will not be modified.
Conclusion
In this tutorial, you learned how to use Python to check if a string is empty or blank. You first learned how to create an empty string in Python, using either direct assignment or the string constructor. Then, you learned how to check if a string was empty using the not
keyword and the len[]
function. Following this, you learned how
to work with blank strings, meaning strings that only contain whitespace.
Additional Resources
To learn more about related topics, check out the tutorials below:
- Python: Remove Newline Character from String
- Python zfill & rjust: Pad a String in Python
- Python rfind: Find Index of Last Substring in String
- Python: Remove Special Characters from a String
- Python String Constructor Official Documentation