Algorithmsstring length
String Length (len, bounds, empty checks)
TT
Testlaa Team
May 14, 2026•1 min read
Length is len(s)—number of Unicode code points in Python 3 str. It is not always human-perceived character count (combining marks, emoji sequences). Still, len drives bounds, loops, and complexity proofs.
Why this shows up in the real world
Form validation enforces min and max username lengths. Buffer allocation estimates bytes from string length only when encoding is fixed.
Core idea (explained for students)
Empty string has length 0. Slices use half-open ranges: s[:len(s)//2] for first half. Guard if not s: before dividing or indexing s[0].
Try this in Python
def mid_char(s: str) -> str:
if not s:
raise ValueError("empty")
return s[len(s) // 2]
print(len("hello"), mid_char("abcde"))
Common mistakes
- Confusing
lenwith byte length after UTF-8 encoding. - Off-by-one when using
range(len(s))withs[i+1]inside the loop.
Key takeaways
- Pair
lenchecks with early returns for empty or single-char cases. - For user-visible length, consider
graphemelibraries when product requires it.
Tags:
StringsPythonStudents
