Algorithmscharacter data type
Character Data Type (str, Length-1 Strings, and Code Units)
TT
Testlaa Team
May 14, 2026•1 min read
In Python, a single character is still a str of length 1—there is no separate char type like C++ or Java. Understanding this shapes how you index, compare, and allocate memory when building parsers.
Why this shows up in the real world
JSON parsers treat every token character as part of a stream object. SMS segment counters reason about UTF-16 code units vs user-visible characters—type confusion breaks billing.
Core idea (explained for students)
Use isinstance(x, str) and len(x) == 1 when you truly need one character. bytes literals like b'A' are length-1 byte objects—decode before mixing with str. For Unicode scalars, ord/chr stay on str length-1.
Try this in Python
def is_single_char(x) -> bool:
return isinstance(x, str) and len(x) == 1
print(is_single_char("A"), is_single_char("AB"))
Common mistakes
- Indexing
s[i]returns astr, notNonefor out of range—guard bounds. - Confusing Unicode code points with UTF-8 bytes when measuring “character width.”
Key takeaways
- Treat length-1 strings as your atomic unit in Python string problems.
- Document whether APIs accept
strorbytesat boundaries.
Tags:
StringsPythonStudents
