The easiest way to check whether the string is empty is to use the len function. This function is going to return the length of a string.
my_str = '' print(len(my_str))
If there are no characters, it returns 0.
Calling method directly
The len function from the previous example calls implicitly the __len__() method. We can also call this method directly from the object.
my_str = '' print(my_str.__len__())
This code also returns 0.
Using the “not” keyword
In the previous examples, the string is empty if the result is 0. In this example, we are going to use the boolean type to return True if the string is empty.
my_str = '' print(not my_str)
This code prints True as a result.
If you want the function to return False, you can’t just remove the not keyword because it’s going to print viariable contents, which in our case is ”. You can do it by using the bool function.
This code is going to return True.
We can modify this it to display a message informing us whether the string is empty or not.
my_str = '' if not my_str: print("String is empty") else: print("String is not empty")
This code prints this message on the console.
String is empty
The equation operator (=)
The fourth way to check the string is to use the equation sign. In this case, we are going to check whether the string equals an empty string.
my_str = '' if my_str == '': print("String is empty") else: print("String is not empty")
The result of this code is the same as before.
What is an empty string?
We treated “” as an empty string. All the previous examples have worked well so far. But you can also treat ” “, or ” ” as an empty string.
To deal with this problem, you can use the strip() method.
my_str = ' ' print(len(my_str)) print(len(my_str.strip())) print(not my_str) print(not my_str.strip())
This are the results.
3 0 False True