Python len string: Get String Length in Python
python len string: Learn how to use Python's len() to get string length, handle Unicode correctly, and understand why it's O(1).
python len string requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.
When you need the number of characters in a string, Python's built-in len() is the standard tool. For a str object, len(s) returns the count of Unicode code points, not bytes. This is a fundamental behavior that affects how you handle text, especially when working with non-ASCII characters.
s = "hello" print(len(s)) # 5
The len() function works by calling the object's __len__ method. For strings, that method returns the precomputed length stored in the internal representation. That means you don't need to import anything or write a custom loop.
How len() Works on Strings
len() is a built-in function that accepts any object with a __len__ method. For strings, it returns the number of characters in the string. This includes spaces, punctuation, and newline characters.
text = "Hello, world!" print(len(text)) # 13
An empty string has length zero:
empty = "" print(len(empty)) # 0
The function never raises an exception for a valid string. It is the canonical way to determine string length in Python, and you will see it used throughout the standard library and third-party code.
len() and Unicode Characters
Python 3 strings are sequences of Unicode code points. len() counts code points, not bytes. This distinction matters when your text contains accented characters, emoji, or characters from scripts like Chinese or Arabic.
s = "héllo" print(len(s)) # 5
Here é is a single code point, so the length is 5. If you need the number of bytes in a UTF-8 encoding, you must encode first:
s = "héllo" print(len(s.encode("utf-8"))) # 6
The encoded bytes include a two-byte representation for é. This distinction is critical when working with network protocols, file formats, or database columns that specify byte limits.
Some Unicode characters, like certain emoji, are represented by multiple code points. For example, the family emoji 👨👩👧👦 consists of several code points combined with zero-width joiners. len() will count each code point, which may not match your visual expectation of "one character."
family = "👨👩👧👦" print(len(family)) # 7
If you need grapheme clusters (what users perceive as characters), you need a library like regex or grapheme. For most string manipulation, len() is sufficient, but be aware of this behavior when validating user input or truncating text.
Common Mistakes and Edge Cases
A frequent mistake is calling len() on None or on a non-string object. len() only works on objects that implement __len__. Passing None raises a TypeError:
value = None try: print(len(value)) except TypeError as e: print(e) # object of type 'NoneType' has no len()
Similarly, integers and floats do not have a length. If you need to handle multiple types, check the type first or use a helper function.
Another edge case is the difference between str and bytes. len(b"hello") returns 5, but that is the number of bytes, not characters. This is consistent with the fact that bytes is a sequence of integers in the range 0-255.
b = b"hello" print(len(b)) # 5
When you read data from a file or network socket, you often get bytes. Converting to str with the correct encoding changes the meaning of length. Always be explicit about which type you are measuring.
Performance: Why len() Is O(1)
For strings, len() runs in constant time. The string object stores its length as a field, so retrieving it does not require scanning the entire string. This is different from languages like C, where strlen must iterate until it finds the null terminator.
This O(1) behavior means you can call len() on very large strings without worrying about performance. It is safe to use inside loops or frequently called functions. The same applies to lists, tuples, and other built-in collections that store their size internally.
There is no need to cache the length of a string in a separate variable for performance reasons. The function call overhead is minimal, and the operation itself is just a field read. If you are doing many length checks, the cost is negligible compared to other string operations like concatenation or slicing.
Alternatives to len() for String Length
You might see code that uses sys.getsizeof() to measure string size. That function returns the memory footprint of the object, including overhead, not the number of characters. It is not a substitute for len().
import sys s = "hello" print(sys.getsizeof(s)) # 54 (on CPython, varies by version)
The exact value depends on the Python implementation and the string's internal representation. sys.getsizeof() is useful for memory profiling, but not for determining string length.
Another alternative is to use a loop to count characters manually. This is unnecessary and error-prone. len() is the idiomatic, readable, and fastest approach.
def manual_len(s): count = 0 for _ in s: count += 1 return count
This loop is O(n) and slower than len(). It also fails to handle certain edge cases correctly if you are not careful with iteration. There is no reason to use it in production code.
Practical Usage in Real Code
String length checks are common in validation, formatting, and data processing. For example, you might enforce a maximum length on a username or a comment field:
username = input("Enter username: ") if len(username) > 20: print("Username too long") else: print("Username accepted")
When working with text files, you might read lines and filter by length:
with open("data.txt") as f: long_lines = [line.strip() for line in f if len(line.strip()) > 100]
In these cases, len() provides a clear, direct way to express the condition. It works consistently across Python versions and implementations, so you can rely on it in any environment.
One subtle point: len() counts code points, so if you are validating a field that should be limited by the number of visible characters, you may need to handle grapheme clusters separately. For most ASCII-based validation, len() is exactly what you need.
Another common pattern is padding or truncating strings to a fixed width. len() helps you determine how much padding is required:
def pad_to_width(s, width): if len(s) >= width: return s return s + " " * (width - len(s))
This function uses len() to compute the difference. It is simple and efficient. The O(1) nature of len() means you can call it multiple times without concern.
When you need to handle both str and bytes in a single code path, be explicit about what you are measuring. You might write a helper that returns the length in human-readable characters, but only for str:
def char_length(value): if isinstance(value, str): return len(value) elif isinstance(value, bytes): return len(value.decode("utf-8")) else: raise TypeError("Expected str or bytes")
This avoids confusion between byte counts and character counts. The decision to count characters or bytes depends on the context. For user-facing text, use characters; for storage or transmission, use bytes.
Understanding how len() behaves on strings is a small but important part of writing correct Python. It is a built-in that you will use constantly, and knowing its semantics helps you avoid subtle bugs with Unicode and encoding.