Check if a String is Empty
Quick Overview
An empty string is falsy, so `if not s:` covers it without calling `len()`. That same test also catches `None`, which is usually what you want and occasionally the bug.
Deep Dive
1. The Challenge: Empty String Detection
Create a function is_empty(s) that returns True if a string is empty and False otherwise.
2. Why It Matters
Validating empty text input prevents processing null values when handling form submissions or user comments.
3. The Python Solution
In Python, an empty string "" is falsy. You can check not s or check if len(s) == 0:
def is_empty(s):
return len(s) == 0
# Pythonic Truthiness Alternative
def is_empty_pythonic(s):
return not s
# Testing our function
print(is_empty("")) # Output: True
print(is_empty(" ")) # Output: False (contains space character!)
print(is_empty("a")) # Output: False
4. Empty String Truthiness Model
""(Length 0) evaluates toFalsein boolean context." "(Space character, length 1) evaluates toTrue. To check if a string is only whitespace, usenot s.strip().
5. Common Mistakes
- Confusing Empty String with Space:
" "is NOT an empty string! If you want whitespace-only strings to count as empty, callnot s.strip().
6. Next Steps
Use not s for Pythonic empty checks. Next, let's compare string lengths!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.