String Methods · Exercises
Beginner

String Methods Exercises

4 exercises that build on the Python String Methods lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A string method is a built-in function called on text with a dot, such as text.strip() or text.split(), that returns a new string, list or value without changing the original. By the end you can clean, split, search, pad and reformat text with string methods, chain them together, and explain why you must store the result. You will practise: Tidy a typed name; Predict the string methods; Fix the slug builder; Parse a messy record.

0 / 4 completed

String Methods practice exercises

1. Tidy a typed name

Write code Easy

Write a function clean_name(raw) that returns the name with spaces removed from both ends, repeated inner spaces collapsed to one, and each word capitalised. Example: " mAYA rao " becomes "Maya Rao".

Your code
def clean_name(raw):
    pass

2. Predict the string methods

Predict the output Easy

Type exactly what this program prints. Watch out for repr() quotes, the partition tuple and what find() returns when nothing matches.

Read this code
text = "  Data,Science,Python  "
print(text.strip().split(","))
print("a-b-c".replace("-", "", 1))
print("report.final.csv".rpartition(".")[2])
print("42".zfill(5), "7".rjust(3, "*"))
print("hello".find("z"), "hello".count("l"))

3. Fix the slug builder

Fix the bug Medium

slugify(title) should turn " Hello World " into "hello-world", but it returns the original text unchanged. Fix the function.

Your code
def slugify(title):
    title.strip()
    title.lower()
    title.replace(" ", "-")
    return title

4. Parse a messy record

Write code Hard

Write parse_record(line) for lines like " asha kumar , 21 , NEW delhi ". It returns a dict {"name": ..., "age": ..., "city": ...} where name and city are stripped and title-cased and age is an int. If the age text is empty or not all digits, use None for the age.

Your code
def parse_record(line):
    pass

Next lessonPython f-Strings

More Python String Methods examples · All Python exercises