The length of a string
You met the function len (short for length) in part 2: it tells how many characters a string has. Every character counts: letters, digits, spaces and punctuation alike. This module puts it to work.
print(len("hello"))
print(len("hello there!"))
print(len(""))
5
12
0The empty string "" has no characters, so its length is 0. Note that len counts characters, not words: "hello there!" is two words but 12 characters, the space and the ! included.
len gives back a whole number, so you can use it wherever a number fits. In a condition, len(name) < 3 is True for a name of fewer than three characters, and len(first) > len(second) compares two strings by their length. In a calculation, 10 - len(word) tells how many characters a word lacks from 10. And it can be the number of times to repeat a string. This program underlines whatever the user types:
title = input("Title: ")
print(title)
print("-" * len(title))
Loops and stringsTitle: Loops and strings
Loops and strings
-----------------Lining up text
The length is also what you need to line text up. When you add numbers on paper, you write them in a column lined up on the right, ones under ones and tens under tens. A program can do the same: to put a number at the right edge of a column 6 characters wide, print 6 - len(number) spaces in front of it. Here the numbers are strings, since len counts characters; int turns them into numbers for the sum, and str turns the sum back into a string:
first = "385"
second = "1250"
total = str(int(first) + int(second))
print(" " * (6 - len(first)) + first)
print(" " * (6 - len(second)) + second)
print("-" * 6)
print(" " * (6 - len(total)) + total)
385
1250
------
1635The parentheses matter. Without them, " " * 6 - len(first) would first make a string of 6 spaces and then try to subtract a number from it, which is an error.
Numbers have no length
len counts the characters of a string. A number isn't a string, so it has no length:
year = 2026
print(len(year))
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(len(year))
~~~^^^^^^
TypeError: object of type 'int' has no len()To count the digits of a number, make it a string first: len(str(year)) is 4.