Learn Without Walls
← Back to Module 7

Module 7: Practice Problems

15 problems to reinforce your understanding of Python strings. Try to solve each problem before looking at hints and solutions!

Problem 1: Case Conversion

Easy

Given text = "hello, WORLD!", print the string in all uppercase, all lowercase, and title case.

Use .upper(), .lower(), and .title() methods.

text = "hello, WORLD!"
print(text.upper())    # HELLO, WORLD!
print(text.lower())    # hello, world!
print(text.title())    # Hello, World!

Problem 2: Strip and Clean

Easy

Given dirty = " Python Programming ", strip the whitespace and print the result with its length.

Use .strip() and len().

dirty = "   Python Programming   "
clean = dirty.strip()
print(f"'{clean}' has {len(clean)} characters")
# 'Python Programming' has 18 characters

Problem 3: Count Characters

Easy

Count how many times the letter "a" appears in "banana bread and jam" (case-insensitive).

Convert to lowercase first, then use .count().

text = "banana bread and jam"
count = text.lower().count("a")
print(f"Letter 'a' appears {count} times")
# Letter 'a' appears 6 times

Problem 4: startswith and endswith

Easy

Given a list of filenames ["report.pdf", "photo.jpg", "data.csv", "image.png", "notes.pdf"], use a list comprehension to find all PDF files.

Use .endswith(".pdf") in the comprehension filter.

files = ["report.pdf", "photo.jpg", "data.csv", "image.png", "notes.pdf"]
pdfs = [f for f in files if f.endswith(".pdf")]
print(pdfs)
# ['report.pdf', 'notes.pdf']

Problem 5: String Replacement

Easy

Given text = "I love Java. Java is great!", replace all occurrences of "Java" with "Python".

Use .replace("Java", "Python").

text = "I love Java. Java is great!"
result = text.replace("Java", "Python")
print(result)
# I love Python. Python is great!

Problem 6: Extract Substring

Medium

Given email = "student@university.edu", use slicing or find() to extract the username (before @) and the domain (after @).

Use .find("@") to get the position, then slice before and after it.

email = "student@university.edu"
at_pos = email.find("@")
username = email[:at_pos]
domain = email[at_pos + 1:]
print(f"Username: {username}")
print(f"Domain: {domain}")

Problem 7: Palindrome Checker

Medium

Write code that checks if a word is a palindrome (reads the same forwards and backwards). Test with "racecar", "hello", and "level". Ignore case.

Convert to lowercase, then compare with [::-1].

def is_palindrome(word):
    word = word.lower()
    return word == word[::-1]

for w in ["racecar", "hello", "Level"]:
    print(f"'{w}' is palindrome: {is_palindrome(w)}")

Problem 8: Word Counter

Medium

Given a sentence, count the number of words using split(). Test with " Python is really fun " (note the extra spaces).

split() without arguments automatically handles multiple spaces.

sentence = "  Python  is   really   fun  "
words = sentence.split()
print(f"Words: {words}")
print(f"Word count: {len(words)}")
# Words: ['Python', 'is', 'really', 'fun']
# Word count: 4

Problem 9: CSV to Sentence

Medium

Given csv = "Alice,30,Engineer", split it and create the sentence "Alice is 30 years old and works as an Engineer."

Split on "," and use an f-string to build the sentence.

csv = "Alice,30,Engineer"
name, age, job = csv.split(",")
print(f"{name} is {age} years old and works as an {job}.")

Problem 10: Build a Path

Medium

Given the list ["home", "user", "documents", "report.pdf"], join them with "/" to create a file path.

Use "/".join(list).

parts = ["home", "user", "documents", "report.pdf"]
path = "/".join(parts)
print(path)
# home/user/documents/report.pdf

Problem 11: Title Case Names

Medium

Given names = "john doe, jane smith, bob jones", split by comma, strip each name, title-case each, and print the results.

Split on ",", then use a list comprehension with .strip().title().

names = "john doe, jane smith, bob jones"
clean_names = [n.strip().title() for n in names.split(",")]
print(clean_names)
# ['John Doe', 'Jane Smith', 'Bob Jones']

Problem 12: Find All Positions

Hard

Find all positions where "is" appears in "This is a string. This is Python."

Use a while loop with find(), updating the start position after each match.

text = "This is a string. This is Python."
search = "is"
positions = []
start = 0

while True:
    pos = text.find(search, start)
    if pos == -1:
        break
    positions.append(pos)
    start = pos + 1

print(f"Found at positions: {positions}")
# Found at positions: [2, 5, 20, 23]

Problem 13: Clean Phone Number

Hard

Given phone = "(555) 123-4567", remove all non-digit characters to get "5551234567". Use a list comprehension with join().

Use "".join([c for c in phone if c.isdigit()]).

phone = "(555) 123-4567"
clean = "".join([c for c in phone if c.isdigit()])
print(clean)
# 5551234567

Problem 14: Initials Generator

Hard

Given name = "john michael smith", create the initials "J.M.S." using split, indexing, and join.

Split the name, take the first character of each word with [0].upper(), then join with ".".

name = "john michael smith"
initials = ".".join([w[0].upper() for w in name.split()]) + "."
print(initials)
# J.M.S.

Problem 15: Log Parser

Hard

Parse this log entry: "2024-03-15 09:30:45 WARNING Disk space low". Extract the date, time, level, and message into separate variables and print each.

Use .split(" ", 3) to split into exactly 4 parts.

log = "2024-03-15 09:30:45 WARNING Disk space low"
date, time, level, message = log.split(" ", 3)
print(f"Date: {date}")
print(f"Time: {time}")
print(f"Level: {level}")
print(f"Message: {message}")
Take the Module Quiz →