Python String Length: len(), Unicode, and Bytes

Python string length is usually measured with len(text), but the result depends on what the string contains and what “length” means for the application. For a Python str, len() counts Unicode code points. For a bytes value, it counts bytes. A user may see one grapheme cluster or one emoji while the underlying text contains several code points and more encoded bytes.

Quick answer

Use len(text) to count Python string code points. Use len(text.encode("utf-8")) to count UTF-8 bytes. Use len(data) for a bytes object. For a UI character limit, decide whether the product means code points, grapheme clusters, display columns, or bytes before choosing a solution. Those measurements are not interchangeable.

The official len() documentation defines the built-in operation as the number of items in an object. The object type therefore matters. This article keeps the common Python count separate from encoding and display-width questions.

Python string length diagram comparing Unicode code points UTF-8 bytes grapheme clusters and display columns
len(str) counts code points, len(bytes) counts bytes, and what a user sees can be a different measurement.

Count Python string code points

For a Python str, len() returns the number of Unicode code points in the string. ASCII text often makes this look identical to the number of visible characters, but more complex text can expose the difference.

text = "Python"
accented = "café"

print(len(text))
print(len(accented))
print(list(accented))

A code point is an abstract Unicode value, not necessarily a complete user-perceived character. The count is still the correct Python string length for slicing, indexing, and many protocol rules, as long as those rules are defined in terms of code points.

Python Pool infographic showing a string, len, characters, and integer length result
len(string) counts Unicode code points in the Python string.

Count bytes after encoding

When a protocol, database column, or file format limits bytes, encode the string first and then call len(). UTF-8 uses one byte for many ASCII characters and multiple bytes for many other code points.

text = "café"
utf8_data = text.encode("utf-8")

print(len(text))
print(len(utf8_data))
print(utf8_data)

Do not truncate encoded bytes arbitrarily and decode them without an error policy. Cutting through a multi-byte UTF-8 sequence can produce invalid data. If a byte limit is strict, build the encoded value incrementally or decode with a deliberate strategy.

Understand emoji and combining marks

An emoji sequence may contain several code points joined by zero-width joiners. A letter with a combining accent may also contain a base code point and a combining mark. Python's len() counts those code points individually, even if the text is displayed as one user-perceived character.

examples = ["A", "e\u0301", "👨‍👩‍👧‍👦"]

for value in examples:
    print(repr(value), len(value), len(value.encode("utf-8")))

If the application promises a “character” limit to users, document whether that means code points or grapheme clusters. For grapheme-aware behavior, use a library that understands Unicode text segmentation rather than trying to count special cases by hand.

Python Pool infographic comparing text, Unicode code points, graphemes, and displayed characters
Python length counts code points, which may differ from user-perceived grapheme count.

Measure a list of strings

Calling len() on a list returns the number of items in the list, not the total number of characters in all strings. Use a sum when the application needs aggregate text length, and be clear about whether separators are included.

parts = ["Python", "data", "tools"]
item_count = len(parts)
character_count = sum(len(part) for part in parts)
joined_count = len(" ".join(parts))

print(item_count)
print(character_count)
print(joined_count)

These three counts answer different questions. The item count is useful for pagination or records; the aggregate count is useful for analysis; the joined count includes the spaces that the final display adds.

Check a string limit safely

A simple code-point limit can be expressed with len(). Validate the type first when input can be missing or numeric. Avoid using a broad conversion to str() unless the product explicitly wants to stringify every value.

def within_code_point_limit(value, limit):
    if not isinstance(value, str):
        raise TypeError("value must be a string")
    if limit < 0:
        raise ValueError("limit must not be negative")
    return len(value) <= limit

print(within_code_point_limit("Python", 10))

For a byte limit, encode and test the encoded length. For a display limit, use a display-aware rule. Naming the helper after the measurement prevents a future caller from assuming that a code-point limit is a byte limit.

Python Pool infographic comparing text, UTF-8 encoding, bytes, and byte length
Encoding text to bytes can produce a different length than the original string.

Find the length of a file line

Text read from a file includes newline characters depending on how it is read. Decide whether the newline belongs in the measurement. rstrip() can remove more than a newline if called without an argument, so use a targeted removal when other whitespace matters.

line = "Python\n"
without_newline = line.removesuffix("\n")

print(len(line))
print(len(without_newline))

When files may use different newline conventions, open them in text mode with the intended newline handling or normalize line endings before measuring. The correct count depends on whether the limit applies to stored data or displayed text.

Use a length hint for custom objects

For custom objects, len(obj) calls the object's __len__() implementation. That method should return a nonnegative integer. A custom class can define length as records, bytes, tokens, or another domain-specific unit, but the unit should be documented.

class Message:
    def __init__(self, text):
        self.text = text

    def __len__(self):
        return len(self.text)

message = Message("Hello")
print(len(message))

Do not assume that every object with a length behaves like a string. Check the type and the class contract when a helper accepts arbitrary collections or custom domain objects.

Python Pool infographic testing empty strings, combining marks, whitespace, encoding, and validation
Define whether length means code points, graphemes, bytes, visible characters, or storage units.

Common mistakes

  • Calling len() on a list and expecting total character count.
  • Confusing Unicode code points with UTF-8 bytes.
  • Assuming one emoji or grapheme cluster always equals one code point.
  • Counting a newline without deciding whether it belongs to the field.
  • Cutting UTF-8 bytes in the middle of a multi-byte sequence.

The practical rule is to name the unit first: code points, bytes, items, grapheme clusters, or display columns. Then use the operation that measures that unit. len() is dependable when the object type and the intended unit are explicit.

Define the limit in the product requirements

A good text-limit requirement says what is measured and when. For example, a database may limit UTF-8 bytes, an API may limit code points, and a mobile interface may limit grapheme clusters or display columns. Writing the unit prevents a technically correct len() check from enforcing the wrong rule.

Keep validation and truncation separate. First determine whether the value exceeds the permitted unit, then apply a deliberate truncation algorithm that preserves valid text and communicates what was removed. Never cut encoded bytes merely because their count is convenient.

For nearby string operations, compare removing characters and extracting a Python substring. Read remove character from string python and python substring for the related workflow.

Frequently Asked Questions

Frequently Asked Questions

How do I find a Python string length?

Call len(text); for a str it counts Unicode code points in the string.

How do I count string bytes in Python?

Encode the string first, such as len(text.encode('utf-8')), or call len() directly on a bytes object.

Why can an emoji count as more than one character?

An emoji sequence may contain multiple Unicode code points even when it appears as one user-perceived character.

Does len() count the newline in a string?

Yes, if the newline character is present; remove it deliberately when the measurement should exclude line endings.

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Nobody
Nobody
5 years ago

There is one best way to get the length of a string, which is using len(). And then there are 4 other more or less bad ways to get the length. And the getsizeof() can even produce completely wrong results, because it returns the size of the object.

For example:

>>> import sys
>>> sys.getsizeof('föö') - sys.getsizeof('')
27
>>> 
>>> help(sys.getsizeof)
Help on built-in function getsizeof in module sys:


getsizeof(...)
    getsizeof(object [, default]) -> int
    
    Return the size of object in bytes.
Python Pool
Admin
5 years ago
Reply to  Nobody

Hi, thank you for your explanation.

Yes, getsizeof() is a non-practical way to find the length of string but to make aware of such hidden functions we’ve mentioned it.
I’ve updated the getsizeof() section with a special note.

Pratik Kinage
Admin
5 years ago
Reply to  Nobody

So our x variable manages which player will play a specific turn. So, if x is even i.e x%2 == 0 then player1 will play the game. Otherwise, player2 will play the game.
Then, we’ll change the text of the button by calling the specific button widget. In this case, b1.config(text=y) is used. Moreover, the boards[number] stores the value of each player’s turns.