Compare Strings by Character Length
Quick Overview
`len()` on a `str` counts characters, not bytes, so an accented letter still counts as 1. It is `O(1)` because Python stores the length rather than walking the string.
Deep Dive
1. The Challenge: Comparing String Lengths
Create a function comp(str1, str2) that returns True if two strings have the same number of characters, and False otherwise.
2. Why It Matters
Length comparison is used in password validation rules, string anagram matching, and data alignment algorithms.
3. The Python Solution
Compare len(str1) == len(str2):
def comp(str1, str2):
return len(str1) == len(str2)
# Testing our function
print(comp("AB", "CD")) # Output: True (2 == 2)
print(comp("ABC", "DE")) # Output: False (3 != 2)
print(comp("hello", "edabit"))# Output: False (5 != 6)
4. How len() Executes
In Python, len() runs in O(1) constant time because string objects store their character length metadata directly in CPython structure headers.
5. Common Mistakes
- Comparing Strings Directly Instead of Their Lengths: Writing
str1 == str2compares character content, NOT length! Ensure you wrap both strings withlen().
6. Next Steps
Use len() to compare collection counts. Next, let's concatenate first and last names!
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.