🐍 Python for Everyone

← Back to exercises

Chapter 6 Practice Bank 50-65 min, hands-on

Practice Bank: Strings Deep Dive

A deeper set of practice problems, organized by topic, for extra reps beyond the main exercises — including scenario-based problems written in the same style you'll meet in real interviews. Uses everything from Chapters 1-5 plus this chapter's own toolkit: len(), indexing/slicing, the string methods from the lesson, f-strings, and iterating a string or a .split() result with a bare for-loop. No lists/dicts, comprehensions, functions, or try/except yet.

How to run these Download starter.py below, then run it from a terminal with python3 starter.py.

Topic 1: Indexing & Slicing

1 First and last character

Find # TODO 1.1. Given word = "Programming", print the first character with a positive index, then the last character with a negative index.

2 Length and a slice

Find # TODO 1.2. Given phrase = "Hello, World!", print its length with len(), then print phrase[7:12].

3 Every other character

Find # TODO 1.3. Given code = "abcdefghij", print every other character using a slice with a step of 2.

4 Reverse with a slice

Find # TODO 1.4. Given word = "Python", print it reversed using word[::-1].

5 Debug the Code

Find # TODO 1.5. This raises an IndexError because word[len(word)] is one past the last valid index. Fix it.

💼 Scenario

Phone number parser

Find # TODO 1.A. Given phone = "(555) 123-4567", use slicing to pull out just the area code "555".

💼 Interview Prep

Slicing never crashes

Find # TODO 1.B. Prove that word[0:100] on a short string doesn't crash, then explain in a comment why a plain index like word[100] would.

Topic 2: Common String Methods

1 Clean whitespace

Find # TODO 2.1. Clean " mpapasani " with .strip() and print the result wrapped in brackets to prove the spaces are gone.

2 Four ways to change case

Find # TODO 2.2. Given city = "new york", print .upper(), .lower(), .title(), and .capitalize() side by side.

3 Strip the dashes

Find # TODO 2.3. Given phone_raw = "555-123-4567", use .replace() to remove the dashes.

4 Debug the Code

Find # TODO 2.4. This crashes with a ValueError because .index() can't find "cat". Fix it with .find(), which returns -1 instead.

5 Count occurrences and words

Find # TODO 2.5. Count how many times "Hello" appears with .count(), then count the total number of words using .split() and a for-loop.

💼 Scenario

Filename validator

Find # TODO 2.A. Given filename = "server_log_2024.txt", check it with .startswith() and .endswith().

💼 Interview Prep

Case-insensitive login check

Find # TODO 2.B. Show that "Manohar" == "manohar" is False, but their .lower() versions match — and explain why that matters for login checks.

Topic 3: String Formatting with f-strings

1 Embed two variables

Find # TODO 3.1. Given name = "Asha" and age = 22, print a sentence using an f-string.

2 Compute inside the braces

Find # TODO 3.2. Given price = 19.99 and quantity = 3, print f"Total: {price * quantity}".

3 Round with a format spec

Find # TODO 3.3. Given pi_value = 3.14159265, print it rounded to 2 decimal places using :.2f.

4 Debug the Code

Find # TODO 3.4. This prints the literal text {temperature} instead of its value because the string is missing its f prefix. Fix it.

5 Aligned table row

Find # TODO 3.5. Print two name/score rows using :<10 to left-align each name and :>5 to right-align each score.

💼 Scenario

Receipt line

Find # TODO 3.A. Given an item name, quantity, and price, print one receipt line with the line total formatted to 2 decimal places.

💼 Interview Prep

Old style vs. f-strings

Find # TODO 3.B. Print the same sentence built with +/str() and then as an f-string, and explain in a comment why the f-string reads more clearly.

Topic 4: Immutability & String Identity

1 You can't mutate a string

Find # TODO 4.1. Explain in a comment why s[0] = "b" isn't allowed, then build "bat" from s = "cat" correctly using slicing.

2 Same object, then a new one

Find # TODO 4.2. Given a = "hello" and b = a, compare id(a) and id(b) before and after b = b + " world".

3 Watch the id change in a loop

Find # TODO 4.3. Build a string with += inside a range(5) loop, printing id(result) every iteration.

4 Debug the Code

Find # TODO 4.4. This raises a TypeError from trying to mutate word via index assignment. Fix it by rebuilding the string with slicing.

5 Interning two literals

Find # TODO 4.5. Given x = "hello" and y = "hello", compare id(x), id(y), and x is y.

💼 Scenario

Log builder anti-pattern

Find # TODO 4.A. Build a log string with += in a loop, printing its id each time, then explain why this is a real performance problem at production scale.

💼 Interview Prep

Reassignment doesn't ripple

Find # TODO 4.B. Given a = "draft", b = a, then a = "final", print both and explain why b still says "draft".

Topic 5: Searching & Validating Strings

1 in / not in

Find # TODO 5.1. Given word = "python", print whether "th" in word and whether "z" not in word.

2 Validate before converting

Find # TODO 5.2. Given age_input = "25", check .isdigit() before converting it with int().

3 Letters only?

Find # TODO 5.3. Compare .isalpha() on "Asha123" and on "Asha".

4 Case checks

Find # TODO 5.4. Check .isupper() on "PYTHON" and .islower() on "python".

5 Whitespace-only field

Find # TODO 5.5. Given field = " ", check .isspace() to detect a field that's only whitespace.

💼 Scenario

PIN validator

Find # TODO 5.A. Given pin = "4821", combine .isdigit() and len() to check it's a valid 4-digit PIN.

💼 Interview Prep

Why .isalnum() rejects underscores

Find # TODO 5.B. Given username = "user_2024", show .isalnum() is False, then build a custom check with a for-loop that also allows "_".

Topic 6: Real-World Text Processing

1 Clean a messy field

Find # TODO 6.1. Clean " MANOHAR@EXAMPLE.COM " by chaining .strip() and .lower().

2 Tally vowels

Find # TODO 6.2. Loop over a sentence character by character and use the accumulator pattern to count vowels.

3 Parse a log line

Find # TODO 6.3. Given line = "level: ERROR", use .find(":") and slicing to split it into a key and a value.

4 Debug the Code

Find # TODO 6.4. This email comparison should be case-insensitive but isn't, so a validly-typed but differently-capitalized email fails. Fix it.

5 Mask a card number

Find # TODO 6.5. Given card = "4111111122223333", mask everything but the last 4 characters for a receipt.

💼 Scenario

Log line splitter

Find # TODO 6.A. Given a pipe-delimited log line, use .split("|") and a for-loop to print each field.

💼 Interview Prep

Whole words vs. raw substrings

Find # TODO 6.B. Count how many times "the" appears as a whole word vs. as a raw substring with .count(), and explain why they differ.

Checking your work Compare your output against solution.py. Your exact wording doesn't need to match — the goal is that your program runs without errors and does what each TODO asks.
← Exercises Challenges →