In Python, strings are sequences of unicode characters. When working with string data, it is often useful to know the length of a string. In Python, the built-in len()
function can be used to conveniently obtain the length of a string.
In this comprehensive guide, we will cover the following topics related to using len()
to find string length in Python:
Table of Contents
Open Table of Contents
- What is the len() Function
- Syntax and Parameters
- Determining String Length
- Differences from length() Method
- Handling Empty Strings
- Strings with Spaces
- Multiline Strings
- Escape Sequences
- Raw Strings
- Measuring String Length in Bytes
- Built-in Functions for String Length
- Comparison with str() Constructor
- Length of Collections
- Examples and Applications
- Common Errors and Solutions
- Conclusion
What is the len() Function
In Python, len()
is a built-in function used to return the length or size of an object. The len() function takes a single parameter, which can be a string, list, tuple, set, dictionary or other sized objects in Python.
For strings, len() returns the number of characters in the string. The returned length is an integer count of characters. len() is very convenient for quickly getting the length of a string when needed for comparisons, validations, slicing, iterations and other string handling operations.
Syntax and Parameters
The syntax of the len() function is straightforward:
len(object)
Where object
is the string or collection to be measured.
len() takes only one required argument, the object whose length to return. No other arguments are supported.
For example:
length = len(my_string)
This calls len() on my_string
and assigns the integer result to the length
variable.
Determining String Length
To find the length of a string using len(), pass the string as the argument:
my_string = "Hello world"
string_length = len(my_string)
print(string_length)
# Outputs 11
In this example, len(my_string)
returned the length 11. Spaces and punctuation count towards the string’s length.
Some more examples:
str1 = "Python"
print(len(str1)) # 6
str2 = "programming language"
len(str2) # 18
str3 = "Welcome to Python"
len(str3) # 19
As you can see, len() quickly returns the length of any string passed to it, regardless of the contents.
Differences from length() Method
Some languages like Java have a .length() method on strings instead of a len() function. In Python, len() is the preferred way to get string length.
length() also exists for Python strings, but is less commonly used:
my_string = "Hello world"
print(my_string.length()) # 11
The length() method has the same result as len(my_string) in this case. However, len() is simpler, faster and more Pythonic.
Handling Empty Strings
For an empty string, len() will return 0:
empty_string = ""
print(len(empty_string)) # 0
Testing for an empty string using len() can be done as follows:
if len(my_string) == 0:
print("String is empty")
Strings with Spaces
When a string contains spaces, each space counts as a character:
space_string = " "
print(len(space_string)) # 5
So len() counts every visible character, including whitespace characters like spaces and tabs.
Multiline Strings
For multiline strings, len()
includes newline characters:
multiline = """This is a
multiline
string"""
print(len(multiline)) # 24
Each newline \n counts as 1 character towards the total string length.
To remove newlines before getting the length, rstrip() can be used:
print(len(multiline.rstrip())) # 22
Escape Sequences
For special characters specified using escape sequences like \n and \t, each sequence counts as 1 character:
escape_str = "Line1\nLine2\tTab"
print(len(escape_str)) # 14
So \n, \t each add 1 to the string length returned by len().
Raw Strings
Raw strings specified with an r prefix ignore escape sequences:
raw_str = r"Line1\nLine2\tTab"
print(len(raw_str)) # 13
Here, \n and \t do not count as extra characters since the r prefix makes this a raw string literal.
Measuring String Length in Bytes
To get the length in bytes rather than unicode characters, encode the string before passing it to len():
str_bytes = len(my_string.encode('utf-8'))
print(str_bytes)
This encodes the string into a bytes sequence using a specified encoding before measuring its length.
Built-in Functions for String Length
Python has a few other built-in ways to get a string’s length:
-
The count() method finds occurrences of a substring, which can be used to get length:
my_string.count("") # Length
-
Format specifiers like %d and f-strings {len():} also work:
print("Length is %d" % len(my_string)) print(f"Length is {len(my_string)}")
However, len() is best practice - it is faster, simpler, and clearer for finding string length.
Comparison with str() Constructor
The str() constructor can convert an object to a string:
str(42) # "42"
Internally, str() uses len() to determine the length of the string representation:
my_string = "Hello"
print(str(my_string)) # "Hello"
print(len(str(my_string))) # 5
So len() is called automatically when converting objects to str.
Length of Collections
In addition to strings, len() can determine the length of any sized collection in Python:
mylist = [1, 2, 3]
print(len(mylist)) # 3
mytuple = (1, 2, 3)
len(mytuple) # 3
myset = {1, 2, 3}
len(myset) # 3
mybytes = b"abc"
len(mybytes) # 3
len() will return the number of items for any ordered sequences like strings, lists, tuples, ranges, as well as the number of elements in an unordered set.
This makes len() an extremely useful built-in function in Python for strings, collections, and data structures.
Examples and Applications
Now let’s go through some examples of how len() can be used for strings in real programs:
Simple String Length
This example prints the length of a hardcoded string:
my_string = "automobile"
length = len(my_string)
print(length) # 10
Basic usage of len() like this is common for quick length checks.
Length of User Input
We can use len() with input() to get a string length:
user_input = input("Enter some text: ")
input_length = len(user_input)
print("You entered", input_length, "characters")
This allows calculating and reporting the length of user-provided text.
Password Length Validation
To validate a password meets a certain length requirement:
password = input("Enter password: ")
if len(password) >= 8:
print("Password accepted")
else:
print("Password too short! Must be 8+ characters")
len() allows simple length checks like this for validation.
Trim Whitespace and Get Length
We can use .strip() and len() together:
text = " Hello World "
cleaned_text = text.strip() # Remove whitespace
text_length = len(cleaned_text)
print(text_length) # 11
This technique is useful for string cleaning and processing before getting the length.
String Length in a Loop
To iterate through a list of strings and print their lengths:
cities = ["San Francisco", "Los Angeles", "Tokyo"]
for city in cities:
city_length = len(city)
print(city, city_length)
# San Francisco 13
# Los Angeles 11
# Tokyo 5
len() can be called on each iteration for operations involving string length.
Length of String List
To get the total number of characters in a list of strings:
phrases = ["Hello", "World", "Python"]
total_length = 0
for phrase in phrases:
total_length += len(phrase)
print(total_length) # 18
This demonstrates how len() can be used to calculate metrics on collections of strings.
Common Errors and Solutions
Here are some common issues faced when using len() on strings in Python:
-
Forgetting parentheses and calling len as a property instead of function:
length = len my_string # Raises TypeError
Use
length = len(my_string)
instead with parentheses. -
Passing two arguments instead of one:
len(my_string, 2) # Raises TypeError
Call len() with just the string as the single argument.
-
Assigning result to a variable of wrong type:
length = "11" # Incorrect, sets length to a string
Use
length = 11
to assign the integer result to an int variable. -
Using len() on variable before assignment:
print(len(my_string)) # Raises NameError
Be sure to initialize the string to measure before passing to len().
Conclusion
In Python, the len() built-in function is an easy and efficient way to get the length of a string. It takes a string as the argument and returns the count of unicode characters as an integer.
len() works on all Python strings, including empty strings, strings with spaces, multiline strings, raw strings, and more. It can also determine lengths of any other collections like lists and tuples.
In summary, len() should be used for all string length calculations instead of less common approaches like .length() method or .count(). Len() is the preferred Pythonic way to get the size and length of strings and other objects.