HOWTO · Python
How to Get the String Length and Size in Python
Choose len() to count a Python string’s elements or sys.getsizeof() to inspect the string object’s shallow memory size.
On this page
Use len(text) to get the number of elements in a Python string. Use sys.getsizeof(text) when you need the shallow memory size of the string object instead. These measurements answer different questions: a character count is not a byte count, and an object’s memory size is not the length of its text.
Get a string’s character count with len()
The built-in len() function is the usual, efficient way to count the elements in a string. It includes spaces and punctuation, as well as letters and digits. For Python strings, those elements are Unicode code points. A visible symbol made from multiple code points, such as a letter followed by a combining accent or a joined emoji sequence, can therefore appear as one grapheme to a reader while contributing multiple elements to len().
Run this example:
text = "Hello, World!"
print(len(text))
Output:
13
For a direct count, pass the string itself to len(). Python parses string-literal escapes before the function receives the string: "\n" represents a newline, while "\\n" represents a literal backslash followed by the letter n. len() counts the resulting string; it does not parse escapes.
Count characters manually when needed
Manual iteration can help when counting is part of a larger operation. Each iteration over a string yields one code point, so adding one per iteration gives the same element count as len() but takes time proportional to the string length. For ordinary length checks, prefer len().
If the text should be normalized or trimmed first, transform it and then measure the result. For example, text.strip() returns a new string with leading and trailing whitespace removed; len(text.strip()) counts that new string. It does not change text itself. Similarly, lowercasing can change the number of code points for some Unicode text, so measure after the transformation when that is the value your task requires.
Measure a string object’s memory size
For a shallow object-size estimate in bytes, import getsizeof from sys and call it with the string. The returned size includes the string object itself, but not other objects it may reference. It is not a count of characters and is not the number of bytes produced by encoding the text as UTF-8. To measure encoded data, encode the string and measure the resulting bytes value instead.
import sys
text = "Hello, World!"
size_in_bytes = sys.getsizeof(text)
print(size_in_bytes)
Output:
54
This observed memory-size result is implementation- and version-dependent; do not treat 54 bytes as a universal value. Use len() for string length; use sys.getsizeof() when the question is specifically about the shallow size of that object.