To find the length of a string in Python, pass the string to the built-in len() function, like len("hello"). It returns an integer: the number of characters in the string, including spaces and punctuation. That is the shortest working version. You need Python installed (any modern 3.x version works) and a way to run code: the interactive interpreter, a script file, or a notebook. No imports, no libraries, no setup beyond that.
The len() function is one of Python's built-ins, so it is always available. It works on any object that has a length, not just strings: lists, tuples, dictionaries, sets and bytes. For strings it counts characters, which is a simple idea with a few sharp edges once you deal with spaces, escape characters, multi-byte symbols and non-English text. The steps below start with the basics and move through the cases that trip people up.
What You'll Need
- A working Python 3 installation. Check it by running
python3 --version(orpython --versionon Windows) in a terminal. - A way to run Python code: the interactive interpreter (type
python3at the terminal), a saved.pyfile, or an editor/notebook such as VS Code or Jupyter. - Basic familiarity with strings, meaning text wrapped in quotes, either single (
'...'), double ("..."), or triple quotes for multi-line text. - Nothing else.
len()needs no import statement and no third-party package.
Step-by-Step
-
Create a string and store it in a variable. Assign the text to a name so you can reuse it:
message = "Hello, world". Using a variable instead of a literal keeps the example readable and lets you print the same value twice. Keep the quotes consistent, and remember that a string is just a sequence of characters in a fixed order. -
Call
len()on the variable and print the result. Writeprint(len(message)). The output is12. Count it yourself to confirm: H-e-l-l-o (5), comma (1), space (1), w-o-r-l-d (5) adds to 12. The comma and the space both count, which is the single most common surprise for beginners. -
Try it directly on a literal in the interactive interpreter. Open the Python prompt with
python3and typelen("Python"). The interpreter answers6immediately. This is the fastest way to experiment without saving files, and it makes it obvious thatlen()returns an integer you can use in arithmetic. -
Store the result instead of just printing it. Assign
n = len(message)and then usenin comparisons or calculations, for exampleif n > 80: print("Too long"). This pattern is how length checks appear in real code: form validation, truncating display text, or enforcing a database column limit. Keeping the number in a variable avoids callinglen()repeatedly. -
Check an empty string. Run
len("")and you get0. An empty string is falsy, soif not text:andif len(text) == 0:both detect it. For an ordinary truthiness test, the shorterif not text:is more idiomatic, but explicitlen()is clearer when you are reasoning about size. -
Count a string with leading or trailing spaces.
len(" hi ")returns6, because all four spaces count. If you want the length of the visible text only, strip the whitespace first:len(" hi ".strip())returns2. Use.strip()for both ends,.lstrip()for the left, or.rstrip()for the right, depending on what you need. -
Understand how escape characters count. In the source text
"line\nbreak", the two characters backslash and n represent one newline, solen("line\nbreak")returns10, not 11. Similarly,"tab\there"contains one tab character. A tab still occupies a single index in the string even though it looks wide on screen, so the numberlen()gives never matches visual column width. -
Test non-English text. Run
len("café")and you get4. Accented letters that are a single Unicode code point count as one character. However, some symbols are built from several code points, for example an emoji with a skin-tone modifier or a letter with a combining accent; these can produce a number larger than what a human would count. If exact user-perceived character counts matter for your application, you may need a third-party library such asgrapheme, becauselen()counts code points, not visible glyphs. -
Use
len()inside a loop or comprehension for many strings. For a list likewords = ["a", "bee", "cat"], run[len(w) for w in words]to get[1, 3, 3]. To find the longest entry, combine it withmax:max(words, key=len)returns"bee"because it has the greatest length among the candidates (ties return the first one encountered). -
Verify your result with a manual check. For any string you are unsure about, print it with visible markers:
print(repr(text))shows hidden spaces, tabs and escapes in plain form. Then count the characters you see, or compare againstlen(). This one habit resolves most confusion about lengths that look wrong.
Common Mistakes
- Calling it as a string method.
"hello".len()raises anAttributeError. Strings have nolenmethod; the syntax islen("hello"). You may be confusing it with methods like.upper()or.strip(), which do belong to the string. - Calling
lenwithout parentheses. Writinglen(text)is right; writinglenalone refers to the function object itself and prints something like<built-in function len>instead of a number. - Expecting the length to exclude spaces. All characters count: spaces, tabs, newlines, commas, quotes inside the string. If you need a different count, clean the string first or compute it yourself.
- Assuming
len()counts visible characters. For emoji sequences or combining marks, the count can exceed what you see on screen. Joins like emoji with family modifiers can be several code points long. - Passing
Nonetolen().len(None)raisesTypeError: object of type 'NoneType' has no len(). When text comes from a function or a database that might returnNone, check for it first or use a default such astext or "". - Measuring an integer or float by mistake.
len(123)also raisesTypeError. Convert first withlen(str(123))if you truly want the digit count.
Tips
- Because
len()is O(1) for strings, calling it repeatedly in a loop is fine; storing it in a variable is mainly for readability. - Use
len()with slicing to trim text:text[:50]keeps the first 50 characters. Combine with+ "..."for an ellipsis, and remember the result may be 53 characters. - Check length only after normalising input: strip whitespace, and if relevant apply
.lower()or a Unicode normal form, so counts are consistent. - For byte length rather than character length, use
len(text.encode("utf-8")). Accented characters and emoji often take more bytes than one character, which matters for storage limits. - If you need to count words rather than characters, use
len(text.split()), which splits on whitespace.
Troubleshooting
If len() does not return a number, read the error message first; Python names the problem precisely.
- NameError: name 'text' is not defined. The variable does not exist in the current scope. Check spelling, and confirm you assigned it before calling
len(). Inside a function, variables defined elsewhere are not automatically visible. - TypeError: object of type ... has no len(). You passed something that has no length:
None, an integer, a float, or a custom object. Inspect the value withprint(type(text)), then fix the source or convert it to a string. - AttributeError: 'str' object has no attribute 'len'. You used method syntax. Switch to
len(text). - The number looks too high. Hidden characters are the usual cause. Print
repr(text)to expose spaces,\nand\t, then strip or clean as needed. Text pasted from a web page or document often carries trailing whitespace. - The number looks too low. Confirm you are measuring the full string and not a slice, a single index, or a variable that was reassigned. Print the value right before the
len()call. - Results differ between environments. Ensure both use Python 3. Very old Python 2 code handles some text types differently; convert inputs to proper
strand the counts should align.
Frequently Asked Questions
Does len() count spaces in a string?
Yes. Every character counts, including spaces, tabs, newlines and punctuation. len("a b") is 3. Strip whitespace first if you want to exclude it.
How do I get the length of a string without counting spaces?
Remove the spaces, then measure: len(text.replace(" ", "")). That removes only ordinary spaces, not tabs or newlines; use "".join(text.split()) to remove all whitespace.
Why does len() return a different number than the characters I see?
len() counts Unicode code points, not rendered glyphs. Emoji built from multiple code points and letters with combining accents can count as more than one. Use repr() to see exactly what the string contains.
Can I use len() on a list or dictionary?
Yes. On a list, tuple or set it returns the number of items; on a dictionary, the number of key-value pairs. It is the same function, not a string-specific one.
How do I check whether a string is empty?
Compare to zero with len(text) == 0, or use the more idiomatic if not text:. Both are correct for strings, though the second is also true for None, which may matter.
Is len() fast enough to call in a loop over millions of strings?
Yes. Getting the length of a string is a constant-time operation, so calling it inside a loop adds negligible cost compared with the rest of the work.