Python strings are immutable and have more complex handling when discussing their operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and the solution to it. Let’s see different methods of Check if String is Empty Python.
Example
Input:[" "]
Output: Yes
Explanation: In this, We are checking if the string is empty or not.
Check Empty String in Python
Here are different methods to Check if a String is Empty or not in Python.
- Using len()
- Using not()
- Using not + str.strip()
- Using not + str.isspace
- Using list comprehension
- Using Bool
- Using strip methods
- Using “and” Operator + strip() Function
- Using all() Function
- Using try/except
Python Check String Empty using Len()
Using len() is the most generic method to check for zero-length strings. Even though it ignores the fact that a string with just spaces also should be practically considered an empty string even if it’s nonzero.
Python3
test_str1 = ""
test_str2 = " "
print ( "The zero length string without spaces is empty ? : " , end = "")
if ( len (test_str1) = = 0 ):
print ( "Yes" )
else :
print ( "No" )
print ( "The zero length string with just spaces is empty ? : " , end = "")
if ( len (test_str2) = = 0 ):
print ( "Yes" )
else :
print ( "No" )
|
Output
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No
Python Check String Empty using Not()
The not operator can also perform the task similar to len() and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.
Python3
test_str1 = ""
test_str2 = " "
print ( "The zero length string without spaces is empty ? : " , end = "")
if ( not test_str1):
print ( "Yes" )
else :
print ( "No" )
print ( "The zero length string with just spaces is empty ? : " , end = "")
if ( not test_str2):
print ( "Yes" )
else :
print ( "No" )
|
Output
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : No
Python Empty String using not + str.strip()
The problem of an empty + zero-length string can possibly be removed by using strip(), strip() returns true if it encounters the spaces, hence checking for it can solve the problem of checking for a purely empty string.
Python3
test_str1 = ""
test_str2 = " "
print ( "The zero length string without spaces is empty ? : " , end = "")
if ( not (test_str1 and test_str1.strip())):
print ( "Yes" )
else :
print ( "No" )
print ( "The zero length string with just spaces is empty ? : " , end = "")
if ( not (test_str2 and test_str2.strip())):
print ( "Yes" )
else :
print ( "No" )
|
Output
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes
Check Empty String Python using not + str.isspace
Works in a similar way as the above method, and checks for spaces in the string. This method is more efficient because, strip() requires to perform the strip operation also which takes computation loads if no. of spaces are of good number.
Python3
test_str1 = ""
test_str2 = " "
print ( "The zero length string without spaces is empty ? : " , end = "")
if ( not (test_str1 and not test_str1.isspace())):
print ( "Yes" )
else :
print ( "No" )
print ( "The zero length string with just spaces is empty ? : " , end = "")
if ( not (test_str2 and not test_str2.isspace())):
print ( "Yes" )
else :
print ( "No" )
|
Output
The zero length string without spaces is empty ? : Yes
The zero length string with just spaces is empty ? : Yes
Check if String is Empty or Not using List Comprehension
This approach entails parsing the text into a list of characters using list comprehension, then determining whether the list is empty. We can evaluate whether or not the string is empty by assessing the truthiness of the list.
Python3
string = ""
x = [ "no" if len (string)> 0 else "yes" ]
print (x)
|
Output
['yes']
Check Python Empty String or Not using Bool
One approach is using the bool function. The bool function returns False for empty strings and True for non-empty strings. Here’s an example of using the bool function to check if a string is empty or not.
Python3
test_str = ""
if not bool (test_str):
print ( "The string is empty." )
else :
print ( "The string is not empty." )
|
Output
The string is empty.
You can also use the bool function to check if a string is empty or not after removing any leading or trailing whitespaces using the strip method:
Python3
test_str = " "
if not bool (test_str.strip()):
print ( "The string is empty." )
else :
print ( "The string is not empty." )
|
Output
The string is empty.
Python Check if String is Empty using Strip Method
Here we will use Python strip() methods to check string is empty or not.
Python3
s = ""
str = " "
if s.strip():
print (f "string, string1 = '{s}', with no spaces is not empty" )
else :
print (f "string, string1 = '{s}', with no spaces is empty" )
if str .strip():
print (f "string, string2 = '{str}', with spaces is not empty" )
else :
print (f "string, string2 = '{str}', with spaces is empty" )
|
Output
string, string1 = '', with no spaces is empty
string, string2 = ' ', with spaces is empty
Check String is Empty or Not Using “and” Operator + strip() Function
In this approach, the “and” operator is used to combine two tests: determining whether the string is not None and determining whether the string’s stripped version is empty.Leading and trailing whitespace characters are eliminated from the string by the strip() function.
Python3
string1 = ""
string2 = " "
if string1 and string1.strip():
print (f "string, string1 = '{string1}', with no spaces is not empty" )
else :
print (f "string, string1 = '{string1}', with no spaces is empty" )
if string2 and string2.strip():
print (f "string, string2 = '{string2}', with spaces is not empty" )
else :
print (f "string, string2 = '{string2}', with spaces is empty" )
|
Output
string, string1 = '', with no spaces is empty
string, string2 = ' ', with spaces is empty
Python Check if String is Empty Using all() Function
The return value of the all() function requires an Iterable as input. If the Iterable is empty or all of its members are true, the value is true. The all() function may determine if a string is empty or if all of its characters are false (empty string) by receiving the string as an iterable of characters.
Python3
string = ""
if all (char.isspace() for char in string):
print ( "The string is empty" )
else :
print ( "The string is not empty" )
|
Output
The string is empty
The “bool” approach for checking if a string is empty or not has a time complexity of O(1), since it simply checks the truth value of the string, which is a constant time operation. The Auxiliary space is also O(1) since it only requires a single boolean variable to store the truth value of the string.
Python Check Empty String Using Try/Except
Using a try-except block, you may determine in Python whether a string is empty. You can catch and deal with specific exceptions that could arise while your code is being executed by using the try-except block. You can gracefully manage circumstances when you anticipate a probable error, such as when you check for an empty string, by using a try-except block.
Python3
string = ""
try :
string[ 0 ]
print ( "The string is not empty." )
except :
print ( "The string is empty." )
|
Output
The string is empty
Complexity Analysis:
This code has a constant time complexity of O(1) because it only tries to access the first character of the string, which takes the same amount of time regardless of the length of the string.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
24 Jul, 2023
Like Article
Save Article