Use implicit boolean evaluation (if not text:) to check if a string is empty in Python. Following PEP 8, empty sequences—including "", [], (), and {}—evaluate to False in a boolean context (“truthiness”), while any non-empty string evaluates to True.
Basic Example
# 1. Define empty and non-empty string variables
empty_str = ""
greeting = "Hello"
# 2. Check if the string is empty using 'if not'
if not empty_str:
print("The string is empty") # Output: The string is empty
# 3. Check if the string has content using 'if'
if greeting:
print(f"Message: {greeting}") # Output: Message: Hello
Key Details & Edge Cases
- Whitespace-only strings (
" "): A string containing spaces, tabs (\t), or newlines (\n) is not empty (len(" ") == 3), soif not " ":evaluates toFalse. If you want to treat whitespace-only strings as empty, call.strip()first:user_input = " \t\n " if not user_input.strip(): print("String is empty or contains only whitespace") - Variables that might be
None:if not text:evaluates toTruefor both""andNone. If you need to distinguish betweenNoneand an actual empty string"", checktext == ""explicitly (orif text is not None and not text:). - Avoid
len(text) == 0: Whilelen(text) == 0works, it is slower (due to a function lookup) and considered un-Pythonic under PEP 8 guidelines.
Comparison of Empty-String Checks
| Expression | "" (Empty) |
" " (Whitespace) |
None |
Best Used When |
|---|---|---|---|---|
if not s: |
True |
False |
True |
Standard PEP 8 check when s is known to be a str. |
if not s.strip(): |
True |
True |
Raises AttributeError |
Validating user input or form fields where blanks don’t count. |
if s == "": |
True |
False |
False |
Distinguishing an empty string "" from None or 0. |
if len(s) == 0: |
True |
False |
Raises TypeError |
Not recommended in Python; prefer if not s:. |
You must log in or register to comment.
