Algorithmsstring length

String Length (len, bounds, empty checks)

TT
Testlaa Team
May 14, 20261 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 len with byte length after UTF-8 encoding.
  • Off-by-one when using range(len(s)) with s[i+1] inside the loop.

Key takeaways

  • Pair len checks with early returns for empty or single-char cases.
  • For user-visible length, consider grapheme libraries when product requires it.

Tags:

StringsPythonStudents