Python Foundations · Lesson 9 of 12

Strings and formatting

Character indexing, slices and formatted output. Learn through short examples, practical tasks and targeted questions.

← All lessons

Processing strings

Strings are sequences of characters, so indexing and slicing work in much the same way as with lists. Formatted strings can combine text with variable values for readable output. Experiment with a short word and label its character positions.

Watch out: String indexes start at zero. Slices exclude the ending position, which can surprise students when counting characters.

1 · Understand

Character indexing, slices and formatted output. Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

word = "computer"
print(word[0])
print(word[0:3])
score = 87
print(f"Score: {score}%")
Download example .py ↓

2 · Practise

Ask for a word, then print its first and last characters and its length. Handle an empty word.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
word = input("Word: ")
if word:
    print(word[0], word[-1], len(word))
else:
    print("No word supplied")
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

word = "hello"
print(word[5])
Reveal the corrected program and explanation
word = "hello"
print(word[4])

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

What does text[-1] refer to for a non-empty string?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →

APPLY THE IDEA

Use this skill beyond the example

Predict the effect of slicing before running it; the end index is excluded. Remember that a number typed via input() is still text until converted.

Quick check: What does "computer"[0:3] produce?

Check: The substring "com": indexes 0, 1 and 2 are included.