Python does not have built-in methods or attributes like
is_empty specifically designed to check whether a string is empty. However, there are other ways to achieve the same result using the existing functionality of the programming language.
Using a boolean expression
In Python, an empty string is considered “falsy,” meaning it evaluates to
False in a boolean context. Conversely, a non-empty string is considered “truthy” and evaluated as
True. This allows you to directly use the string in boolean expressions to check if it’s empty or not.
text = "" if text: print("Text is not empty") else: print("Text is empty")
Text is empty
Using the len() function
Another way to know if a string is empty is to use the
- Use the
len()function to get the length of the string.
- Check if the length of the string is equal to 0.
Trueif the length is 0; otherwise, return
string_1 = "Sling Academy" string_2 = "" if len(string_1) == 0: print("String 1 is empty") else: print("String 1 is not empty") if len(string_2) == 0: print("String 2 is empty") else: print("String 2 is not empty")
String 1 is not empty String 2 is empty