0%

Working with Text · practice

Measure Text with len()

Python’s len() tells you how many characters a contains.

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
  • len is the function.

  • word is the .

  • The integer 6 is the .

  • The stores that integer in character_count.

len() returns an integer, so its result can take part in arithmetic:

Try it

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 . The space between the words is included in the count.

Task

Use len() to the number of characters in title to title_length.

The program should print:

Python Land has 11 characters.