Use Python’s built-in len() function to get a string’s length: len('hello') returns 5. It counts Unicode code points in the string—not necessarily the number of visible symbols, screen columns, or encoded bytes.
Basic syntax and examples
Call len() with one object in parentheses. For a string, the result is an integer representing how many code points it contains. The function works the same way whether the string is stored in a variable or written directly in the call.
word = 'Python'
print(len(word)) # 6
print(len('')) # 0
print(len('hello!')) # 6
An empty string has length zero. Spaces and punctuation count just like letters, so len('hi there!') returns 9: the two letters, the space, the five letters in “there,” and the exclamation mark. A newline inside a string counts too.
You can store the result, compare it, or use it in a condition. For example, with a user-entered value in name, if len(name) == 0: checks whether the string is empty. In ordinary Python code, an even more direct emptiness check is if not name:; both work for strings, though the latter checks whether the string is false-like rather than explicitly comparing its length.
What Python counts as a string character
Python’s str type represents text as a sequence of Unicode code points. In simple cases, one familiar letter corresponds to one code point, so the result matches what most people mean by character count. For example, len('café') is usually 4 when the final letter is represented as the single code point U+00E9.
The definition matters when text contains special characters. Python counts every code point in the string, including spaces, tabs, line breaks, combining marks, and invisible formatting characters. It does not decide whether a character is meaningful, visible, or printable; it reports the length of the sequence.
This also explains why a string’s length is not its final index. Python indexes from zero, but len(text) counts from one. If text has length 5, its valid single-character indexes are 0 through 4. The last character can be accessed with text[-1], while text[len(text) - 1] expresses the same position less compactly.
Unicode, emoji, and visible symbols
A code point is not always the same thing as a symbol a person perceives as one character. Some accented letters can be represented either as a precomposed code point or as a base letter followed by a combining mark. For instance, the visible “é” may be one code point, or it may be an “e” plus a separate accent code point. The two forms can look identical while producing lengths of 1 and 2.
Emoji make the distinction especially noticeable. A simple emoji such as 😀 is one Unicode code point, so len('😀') returns 1. But many displayed emoji are sequences. A family emoji can combine several people with zero-width joiners; a flag is commonly made from two regional-indicator code points; and a skin-tone variation may add another code point. The displayed symbol can therefore look like one unit while len() returns a larger number.
For example, the laptop-technologist emoji sequence 👩💻 consists of a woman code point, a zero-width joiner, and a laptop code point, so its Python string length is 3. This is expected behavior, not a Python counting bug. If an application needs the number of user-perceived grapheme clusters, it needs Unicode grapheme-cluster rules rather than plain len(). Python’s standard library does not provide a direct general-purpose grapheme-count function; the third-party regex package supports the \X grapheme-cluster pattern.
Normalization can also matter when comparing or measuring text from different sources. The standard-library unicodedata.normalize() can convert text to a chosen Unicode normalization form, such as NFC. Normalize only when it fits the application’s requirements: normalization may make equivalent representations consistent, but it does not turn len() into a visual-symbol counter.
String length versus byte length
Text and encoded data have different lengths. A Python str is text, while bytes is a sequence of byte values. Consequently, len(text) counts code points, but len(data) counts bytes when data is a bytes object.
text = 'café'
print(len(text)) # 4
print(len(text.encode('utf-8'))) # 5
In this example, the letters c, a, and f each take one byte in UTF-8, while é takes two, making five bytes total. UTF-8 uses a variable number of bytes per code point, so a string’s encoded byte length can differ from its Python string length. Other encodings may produce different byte counts.
Use the measurement that matches the job. If you are checking how many code points a Python text value contains, use len(text). If you need the size of its UTF-8 representation—for example, to enforce a byte limit in a protocol—use len(text.encode('utf-8')). If a format specifies another encoding, use that encoding instead. A character limit and a storage or transmission limit are not interchangeable.
How len() works with other objects
len() is a built-in function for objects that have a defined size, not a method exclusive to strings. It also returns the number of items in common containers such as lists, tuples, dictionaries, sets, and ranges. For a dictionary, it counts keys; for a list, it counts elements, not the number of characters inside any strings stored in the list.
print(len(['red', 'blue'])) # 2: list items
print(len({'red': 1})) # 1: dictionary keys
print(len('red')) # 3: string code points
For a custom class, Python can use its __len__() special method to determine the object’s size. That method is expected to return a non-negative integer. This shared interface is why the same built-in function can ask for the size of many different kinds of objects without needing a separate function for each type.
Do not confuse this with calling a string method such as text.length(). Python strings do not have a length() method or a length property. The standard form is len(text), with the object passed as the function’s argument.
Common mistakes and useful checks
One frequent error is trying to use len() on a number. An integer such as 42 has no sequence length, so len(42) raises TypeError. If you want the number of digits in its decimal representation, convert it to a string first: len(str(42)) returns 2. For negative numbers, that conversion also counts the minus sign, which may or may not be what your calculation needs.
Another mistake is forgetting that whitespace counts. A string that looks blank may contain spaces or a newline, and its length will be greater than zero. To test whether a string contains only whitespace, use text.isspace() after accounting for the empty-string case, or use not text.strip() when removing surrounding whitespace is appropriate. Do not use a length check alone to decide whether user input has meaningful content.
Keep an eye out for shadowing the built-in name. If code assigns a value to len, such as len = 5, then a later call like len('abc') will fail because the name now refers to an integer rather than Python’s built-in function. Use another variable name, such as text_length, and restart or correct the scope if the built-in has already been shadowed.
- Use
len(text)for the number of code points in a string. - Use
len(text.encode('utf-8'))when the UTF-8 byte count is what matters. - Use a grapheme-aware approach when counting user-perceived symbols.
- Use a display-width-aware approach when laying out text in a terminal; tabs and wide characters make screen columns different from string length.
Efficiency and choosing the right measurement
For Python’s built-in strings, len(text) is the normal, efficient way to ask for the length. In CPython, the string’s size is available without walking through every code point on each call. By contrast, manually looping over the string just to count its elements does extra work and is less clear. Prefer the built-in function unless the task requires a different definition of “character.”
The best measurement depends on the requirement, not on which count seems most intuitive. A form may limit code points, grapheme clusters, or encoded bytes; a network protocol may impose a byte limit; and a terminal layout may care about display columns. These are separate rules. When implementing a limit, check the specification or interface you are targeting, then name the measurement clearly in the code—for example, code_point_count or utf8_byte_count—to avoid later confusion.
For ordinary text processing, indexing and slicing use the same code-point-based model as len(). A slice such as text[:10] selects up to ten code points, not necessarily ten visual symbols. It can split a combining sequence or a multi-code-point emoji. If a user interface must truncate text without cutting a visible symbol in half, use grapheme-aware segmentation rather than assuming that slicing at a len()-based position is visually safe.
Frequently Asked Questions
What is the Python function for string length?
Use the built-in len() function, as in len(my_string). It returns an integer counting the string’s Unicode code points.
Does len() count spaces and punctuation?
Yes. Spaces, punctuation, and line breaks are part of the string and count as code points. An empty string has length zero.
Why does len() return more than one for an emoji?
Some displayed emoji are sequences of multiple Unicode code points, such as a base emoji plus a joiner or variation. len() counts those code points individually rather than counting the combined display as one symbol.
How do I get the number of bytes in a string?
Encode the string, then measure the resulting bytes. For UTF-8, use len(text.encode('utf-8')). The byte count can differ from len(text).
Does Python use string.length or len(string)?
Python uses len(string). A standard Python string does not provide a length property or a length() method.
Related
- What Is a String in JavaScript? Types, Uses, and Examples
- JavaScript split() Syntax, Examples, and Pitfalls
- F-String in Java: Formatting and Alternatives
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Round to Nearest Quarter: Formula & StepsTo round a number to the nearest quarter (0.25) in Excel, use the formula =MROUND(A1, 0.25). This rounds…
- How to Divide in Excel: Formulas and ExamplesTo divide in Excel, enter a formula with a forward slash, such as =A2/B2, and press Enter. Replace…
- PostgreSQL String Functions and Operators: Practical GuidePostgreSQL string functions and operators let you join, inspect, extract, search, and transform text in SQL. The main…
- HLOOKUP Examples in Excel: Formulas and Common FixesIn Excel, HLOOKUP searches across the first row of a range and returns a value from a specified…
- Concatenate in Excel With Quotes: Formulas and ExamplesTo concatenate text in Excel with quotation marks, join the parts with the ampersand operator (&) and use…
- How to Execute a Function in PostgreSQLExecuting a function in PostgreSQL means calling it so it runs its SQL logic and returns a result.…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.