Python string is a sequence of characters that is enclosed in either single quote, double code, or triple quote. While dealing with string in an application there may be a chance when we need to check the string for null or empty.
A string can be treated null if its size(length) is zero or contains blank space, white space only. However, a string containing white space does not make sense so treated as empty or null.
In this article, we are going to see various scenarios where a string can be treated as null and parallelly seeing how we can identify a string is null or not.
We can use the not operator to check whether the string is null or not. If the string is null then the if condition executed because of the not operator and prints string is empty to the console.
# Take a String
str = ""
# Check whether it is empty
if not str:
print("string is empty")
else:
print("string is not empty")
Output:
string is empty
If a string contains blank spaces that do not make sense and treated as a null string. So, when we test for null string, always use the strip() method to remove all the whitespaces as we did in the below example.
# Take a String
str = " "
# remove white space, if string contains white spaces
str = str.strip()
# Check whether it is empty
if not str:
print("string is empty")
else:
print("string is not empty")
Output:
string is empty
We can use the strip() method inside the if condition to make the code more precise. See the below code.
# Take a String
str = ""
# Check whether string is empty
if str and str.strip():
print("Strin is not empty")
else:
print("String is empty")
Output:
string is empty
In this example, we created a function to check whether the given string is null or not. This function returns a boolean value either true or false.
# Take a String
str1 = ""
# Check whether string is empty
def isBlank (str_val):
return not (str_val and str_val.strip())
result = isBlank(str1)
# Display result
print(result)
Output:
True
This is a single-line solution that returns a boolean value either true or false. We can use it to test if a string is null or not.
# Take a String
str1 = ""
# Check whether string is empty
result = "".__eq__(str1)
# Display result
print(result)
Output:
True