×

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In Python, strings are immutable. They can be changed based on the requirement of the operation. There are many functions in python which are used to manipulate the string. Slicing, looping, indexing, deleting, addition, etc., are mainly used while working with strings. Every string containing spaces is taken as an empty string containing a non-zero size. In this article, we will learn on how to rectify those issues, so we will check whether the taken string is empty or not. To solve this problem, there are six different methods which are:
1. Method using len()

2. method using not

3. method using not+str.strip()

4. method using not+str.isspace

5. method using list comprehension

6. method using bool

Now let us go through every method to check a string using example codes.

1.Using len():

This is the most general method to check whether the string has an element. This method will not consider that a string with only spaces should be empty. To understand this concept better, let us try some example codes.

Code:

# using the method len()
# initialize a string
A_str1 = "hello"
B_str2 = "  "
 
#  check if the string is empty or non empty
print("if The length of the  string without spaces will be empty or not? : ", end="")
if(len(A_str1) == 0):
    print("Yes it is empty")
else:
    print("No not an empty one")
 
# if it prints No
print("The zero length of the string with just spaces is empty ? : ", end="")
if(len(B_str2) == 0):
    print("Yes it is")

Output:

if The length of the  string without spaces will be empty or not? : No not an empty one
The zero length of the string with just spaces is empty ? : No it is not

Explanation:

In the above code, we see that at the start, we initialized two strings, and then we used the len() function for both strings to check whether the given input string is empty or non empty and get the required output.

2. Using not:

This method works similarly to the len() method; we can also check for zero-length strings. And like the len() method, even this method will consider the string with just spaces as non-empty. The not operator in python will protect the string from being taken as an empty string even though it contains spaces.

Let us understand this by looking at an example code below:

Code:

# using not method
# initializing the string
a = ""
b = "  "
 
# checking if the taken string is empty or not
print ("is the zero length string without spaces empty ? > ", end = "")
if(not a):
    print ("Yes, it is")
else :
    print ("No it is not")
 
print (" is the zero length string with just spaces is empty ? > ", end = "")
if(not b):
    print ("Yes it is")
else :
    print ("No it is not")

Output:

is the zero length string without spaces empty ? > Yes it is
 is the zero length string with just spaces is empty ? > No it is not

Explanation:

In the above code, we have first initialized the string using no operation, and we checked whether the string was empty or not.

3.Using not+str.strip():

The problem of having an empty plus a zero-length string can be mostly removed if we use the strip() function. With this function, it will return true if it finds any spaces. So having a track of them can mostly clear the issue. Let us look at an example code for this method:

Code:

# using not + strip() method
# initializing string
a= ""
b= "  "
 
# checking if the string is empty or not
print (" is The zero length string without spaces empty ? > ", end = "")
if(not (a and a.strip())):
    print ("Yes it is")
else :
    print ("No it is not")
 


print ("is The zero length string with just spaces empty ? > ", end = "")
if(not(b and b.strip())):
    print ("Yes it is")
else :
    print ("No it is not")

Output:

is The zero length string without spaces empty ? > Yes it is
is The zero length string with just spaces empty ? > Yes it is

Explanation:

In the above code, as we first initialized the string and, using the not+strip() operation, we checked whether the string is empty or not.

4.Using not+str.isspace:

This method is so similar to the not+strip() method. Apart from that, this method checks for the spaces in the string. Comparatively, this method is more efficient than the previous method. Let us look at an example code to understand this concept better:

Code:

# using not + isspace() method
 
# initializing the string
a = ""
b = "  "
# checking if string is empty
print (" is The zero length string without space empty ? > ", end = "")
if(not (a and not a.isspace())):
    print ("Yes it is")
else :
    print ("No it is not")
 
print (" is The zero length string with just space is empty ? > ", end = "")
if(not (b and not b.isspace())):
    print ("Yes it is")
else :
    print ("No it is not")

Output:

is The zero length string without space empty ? > Yes it is
 is The zero length string with just space is empty ? > Yes it is

Explanation:

In the above code, we have first initialized the string, and using the not+strip() operation, we have checked whether the string is empty or not.

5. Using list comprehension:

In this method, we will give the string as an input, and we will directly use the len() function and compare it with zero, and if the length of the given string is more significant than zero, then it will give output as no else it will give yes and yes indicates it's a non-empty string. Let us look at an example code for better understanding.

Code:

str="  "
x=["non empty" if len(str)>0 else "empty"]
print(x)

Output:

['non empty']

Explanation:

In the above code, we have first initialized the string, and using the list comprehension operation, we checked whether the string was empty or not.

6. Using bool:

Using this function, it doesn't give any other inputs. Instead, it returns true for non-empty strings and false for empty strings. Let us have an example code for this concept.

Code:

# Initializing the string
string1 = " "
 # Check if the string taken is empty or not
if not bool(string1):
    print("FALSE")
else:
    print("TRUE")

Output:

TRUE

Conclusion:

This article has covered all the methods to find an empty string in the python programming language using different example codes.


Related Topics

Loan calculator using Tkinter in Python

Tkinter: Tkinter, part of all common Python distributions, is the de facto method for creating Graphical User Interfaces (GUIs) in Python. The only framework included in the Python standard library is...

4 minutes read.

Google Python Class

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python pynmea2

Define Pynmea2 Python Programming Language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in...

4 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

How to Configure Python Interpreter in Eclipse

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python Packages

A package is a collection of Python modules that share a similar namespace and are generated by putting all of the modules in a single directory with certain special files...

6 minutes read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python data science course

What is meant by Data Science? When processing raw, structured, and unstructured data utilizing various technologies, algorithms, and the scientific method, data science is a detailed study of the enormous quantity...

4 minutes read.

Python Graph

Python Graph: In Computer Science and Mathematics, a Graph is a pictorial representation of a group of objects or elements where some elements are connected using the links. A graph...

5 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Python GUI Programming

GUI (Graphical User Interface) GUI is a graphics-based operating system that uses icons and menus to interact with the user. Python mostly works on CLI (Command Line Interface). Widgets Any user interface has...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

6 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

Screen Rotation app Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Wikipedia module in Python

Wikipedia module in Python: The internet has become an essential part of all of our life which is the largest source of all the information. Therefore, it becomes very important...

7 minutes read.

Python Program to Generate a Random String

The term "random" refers to a group of information or data that can be accessed in any chronological order. To create random strings, a Python program called random is utilized....

6 minutes read.

Python List insert() method

Python List insert() method The list.insert () method in Python inserts an item at the specified position. Syntax list.insert(i, x) Parameter i: This parameter represents a number specifying the position to insert the given value. x: This parameter signifies...

1 minute read.