Working with Text · practice
Measure Text with len()
Python’s len()
word = "Python"
character_count = len(word)
print(character_count)
The output is 6.
Apply the function-call model
len(word) follows the pattern from Chapter 3:
function(argument) -> return value
lenis the function.wordis the. The integer
6is the. The
stores that integer in character_count.
len() returns an integer, so its result can take part in arithmetic:
Every character counts
Spaces and punctuation belong to the string:
print(len("Hi"))
print(len("Hi!"))
print(len("Hi there"))
The results are 2, 3, and 8. The space in "Hi there" counts as one character.
An escape sequence such as \n is written with two code characters, but it represents one newline character inside the string:
print(len("A\nB"))
The result is 3: A, a newline, and B.
The empty string has length zero:
print(len(""))
What does len("Python Land") return?
Measure a course title
Replace the placeholder 0 with a call to len() that measures title.
Keep the title itself unchanged. The program must print:
Python Land has 11 characters.
Use title_length in the existing
Task
Use len() to title to title_length.
The program should print:
Python Land has 11 characters.