0
0
PythonHow-ToBeginner · 3 min read

How to Find Length of String in Python Quickly

In Python, you can find the length of a string using the len() function. Just pass the string as an argument to len(), and it returns the number of characters in that string.
📐

Syntax

The syntax to find the length of a string is simple:

  • len(string): Calls the len() function with the string you want to measure.
  • Returns an integer representing the number of characters in the string, including spaces and special characters.
python
len(string)
💻

Example

This example shows how to use len() to find the length of different strings.

python
my_string = "Hello, world!"
length = len(my_string)
print(f"The length of '{my_string}' is {length}.")

empty_string = ""
print(f"The length of an empty string is {len(empty_string)}.")
Output
The length of 'Hello, world!' is 13. The length of an empty string is 0.
⚠️

Common Pitfalls

Some common mistakes when finding string length include:

  • Trying to use len without parentheses, like len(string) vs len string. The function must be called with parentheses.
  • Confusing string length with byte size. len() counts characters, not bytes.
  • For multi-byte characters (like emojis), len() counts each character as one, which may differ from visual length.
python
wrong = len("hello")
# SyntaxError: missing parentheses in call to 'len'

right = len("hello")
print(right)  # Output: 5
Output
5
📊

Quick Reference

Remember these tips when using len() with strings:

  • Use parentheses: Always call len() with parentheses.
  • Counts characters: Includes letters, spaces, punctuation, and special characters.
  • Empty string: Returns 0.

Key Takeaways

Use the built-in len() function to get the length of a string in Python.
len() counts all characters including spaces and punctuation.
Always include parentheses when calling len(), like len(string).
An empty string has length 0.
For multi-byte characters, len() counts each character as one.