How to check if a string is Null in Python

In this tutorial, you will learn different ways to check whether a String in Python is null or not.

check if a string is Null in Python using len()

Here you will use the len() method as shown below:

String  = ""
if len(string) == 0:
    print("The string is empty")
else:
    print("string is not empty")

Code above will print “The string is empty” as the length of the string is zero.
Note: The above method will print the else statement even if there is a space inside the single/double quote as len() method also considers spaces.

Using isspace() we can check if a string is Null

Here you will use .isspace() method which will help us in identifying whether the string contains some data or does it contains only whitespaces. .isspace() can be implemented as:

String1 = "  "
String2 = "test string"
print(String1.issapce())
print(String2.isspace())

The second technique is better than the first one as it helps us to identify whether there are only whitespaces in string or string also contains some data in it. Output for the above code is:

True
False

.isspace() method will return True if the string contains only white space in it will print False if the string contains even a single non-whitespace character.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *