Next Gen Data Learning – Amplify Your Skills

Blog Home

Blog

Python Empty String: Explained With Examples

by | Python

You’ve been cruising through your Python journey, slicing through lists, taming those wild tuples, and maybe even wrestling with a few ornery object-oriented concepts. But now, you’ve stumbled upon a seemingly simple, yet surprisingly sneaky creature: the empty string.

An empty string is a string that contains no characters. Empty strings can be created in Python using the str() function or assigning a variable with single or double empty quotes. Methods like the len() function or the eq operator can identify when a string is empty or not empty.

As a Python developer, you should recognize the simple and more complex methods to assign and identify empty strings. This article shows you multiple examples.

You’ll also learn essential operations like stripping empty space, concatenation, and working with empty strings in data structures.

Let’s dive in!

3 Ways How to Create an Empty String in Python

python empty string

An empty string is a string with no characters or whitespace. It can be created and assigned to a variable in several ways:

  • Assign to a variable using single or double quotes.

  • Use the str() function.

  • Use the format() function of an empty string.

1. Single or Double Quotes

Using quotes is probably the most common and straightforward method to create an empty string. You can use single or double quotes.

Here is some sample code to demonstrate the assignment of empty strings to two string variables.

empty_string1 = ''
empty_string2 = ""

2. Str() Function

The str() function is an in-built Python function. When you use it with no arguments, it returns an empty Python string.

empty_string3 = str() 

3. Format() Function

The format() method in Python is a string method that formats specified values in a string. You can use it with a literal blank string, as in this code snippet:

empty_string4 = "".format()

3 Simple Ways to Identify An Empty String

python code with magnifying glass

You have several choices for identifying an empty string with Python code. Here are the three simplest ways:

  1. Eq operator (==)

  2. Len() function

  3. Not operator

1. Eq Operator

You can compare a string variable with a quoted empty string using the eq operator to check for equality. This code snippet illustrates how:

if str1 == "": 
     print("The string is empty")

2. Len() Function

The len() function returns the length of Python strings. If the length is zero, the string is empty.

This code checks for a zero-length string:

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

If you think that there may be leading or trailing whitespace characters in blank strings, you can use the strip() method before checking its length. The above code is amended to look like this:

if len(some_string.strip()) == 0:
     print("The string is empty.")

3. Not Operator

In Python, empty strings are considered “falsy” which means they evaluate to False in a Boolean context. A not-empty string evaluates as True.

Here’s how you can use the not operator to check for a falsy value:

if not some_string:
     print("The string is empty.")

How to Use List Comprehension to Check for Empty Strings

illustration of complex code in python editor

This method gets its own section because it’s more complex than the three simple methods we showed above!

You can also use Python list comprehension to check if any string in a given list is empty or non-empty. Suppose you have the following list of strings:

list_of_products = ['Hoodie', '', 'T-Shirt', '', 'Jeans']

Use list comprehension to check if each string is empty:

is_empty = [s == '' for s in list_of_products]

The is_empty variable will now be a list of boolean values. If a value returns True, it’s an empty string. If it returns False, it is a non-empty string.

When you print the is_empty variable, you will see this output:

  • [False, True, False, True, False]

In other words, three values from five have a non-zero size and two values are empty.

How to Strip Whitespace From Strings

We’ve already mentioned the strip() function, which is a built-in method for removing leading and trailing whitespace.

Note that strip() doesn’t just eliminate spaces. It also removes tabs and newline characters from the input string.

Here’s a basic usage example with a variable with five empty spaces:

text = "    "
trimmed_text = text.strip()

The trimmed_text variable will contain an empty string as the original had only spaces.

Stripping whitespace is a common task in data wrangling. Check out this video for more functions:

3 Common Python Operations on Empty Strings

There are several common operations you’ll frequently perform with empty strings. The behavior of these operations may not always be intuitive, especially for those new to programming.

Understanding them can help prevent bugs and confusion. We’ll look at these three operations in more depth:

  1. Concatenation and replication

  2. Conversion to other data types

  3. Inserting into data structures

1. Concatenation and Replication

illustration of plus operator

Although an empty string doesn’t contain any characters itself, it can still be used in operations with other strings. Concatenation using the + operator will simply return the other string:w

s = "" + "Hello"  # s is now "Hello"

Similarly, replicating an empty string any number of times with the * operator will still result in an empty string:

s = "" * 5  # s is still ""

You’re probably not intending to replicate empty strings. But if you are debugging an unexpected empty result after replication, it’s worth checking if the original variable was empty in the first place!

2. Conversion to Other Data Types

An empty string can be converted to certain other data types. For instance, when converting an empty string to a list, the result is an empty list:

l = list("")  # l is now []

However, trying to convert an empty string to an integer or float with int(“”) or float(“”) will raise a ValueError.

3. Inserting into Data Structures

Empty strings can be inserted into various data structures just like any other strings. They can be elements in a list, values in a dictionary, etc.

my_list = ["", "T-Shirts", ""]
my_dict = {"key1": "", "key2": "T-Shirts"}

However, be careful when using empty strings as dictionary keys. While it’s technically possible, it can be confusing and lead to bugs if you’re not careful.

Final Thoughts

Empty strings, while seemingly simple, can present a variety of challenges and considerations in Python programming. By understanding how to create, recognize, and handle them, you can better equip yourself to write clean, efficient, and error-free code (use this cheat sheet for more help).

You should follow and practice the examples in this article to get familiar with using empty strings in concatenation, within data structures, and converting to other data types.

This adds to your toolkit for Python proficiency and puts you further on your journey to becoming an expert Python developer

Related Posts