×

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

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Difference between python list and tuple

In this tutorial, we will understand the key differences between python lists and tuples in python. Firstly, let us see the similarities between Lists and Tuples. Both are two data types...

4 minutes read.

Python | Read csv using pandas.read_csv()

Python is an excellent language for performing information analysis, owing to the fantastic biological system of information-driven python packages. Pandas is one of those packages that make taking in and...

4 minutes read.

ComboBox in Python

Python includes several graphical user interface (GUI) libraries, including PyQT, Tkinter, Kivy, WxPython, and PySide. Tkinter is the most commonly used GUI module in Python because it is simple and...

2 minutes read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

How to import numy in python

How to Install NumPy in Python Python is a vast ocean of libraries, modules, and different functions. It has a solution for almost everything. Using Python, we can simplify even a...

3 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Marshmallow

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python List index() method

Python List index() method The list.index () method in Python returns the position at the first occurrence of the specified value. Syntax list.index(x[, start[, end]]) Parameter element – This parameter represents the element whose lowest index will be returned. start (Optional)...

2 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python Percentage Sign

In Python, the percentage sign significantly completes two things. They are: It goes about as a Modulo administrator. It helps in string organizing. Allow us to see every one of them plainly. Modulo operator: Like...

2 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Import Module in Python

In this article, you will learn everything about “ Import ” in Python. Modules in python that are already created can be accessed and used in another code by importing the...

6 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.