3. Strings
3.4 String practice problems
Highlights & notes
Select lesson text to highlight it, or tap Add note.
Bookmarks
Bookmark a lesson to see it here.
Three real-world text problems that use only what this chapter taught: indexing, slicing and string methods. Run each cell with ▶ or Shift+Enter. When your output matches, the question turns green by itself.
split() breaks text into a list of pieces. Read one piece by its position, such as parts[0] for the first and parts[1] for the second.
Problem 1: Read an email address ✓ Solved
An email address is a username and a domain joined by @.
Using email = "ankit.kothari@hotmail.com", print:
- the username (before @)
- the domain (after @)
- the person's full name in title case, built from the username
Expected output
Username: ankit.kothari Domain: hotmail.com Name: Ankit Kothari
Reference solution
email = "ankit.kothari@hotmail.com"
parts = email.split("@")
username = parts[0]
domain = parts[1]
full_name = username.replace(".", " ").title()
print("Username:", username)
print("Domain:", domain)
print("Name:", full_name)
Problem 2: Mask a mobile number ✓ Solved
Apps hide most of a phone number on screen. Show only the last four digits and replace every other digit with *.
Your code should work for a number of any length, so use len() instead of counting by hand.
Expected output
******4949
Reference solution
mobile = "9959594949"
masked = "*" * (len(mobile) - 4) + mobile[-4:]
print(masked)
Problem 3: Clean a messy name record ✓ Solved
A form saved a name and an age as one messy string: "AnKIT Kumar KOTHAri,20 ".
Print the first, middle and last name in title case, and the age as a number.
Expected output
First name: Ankit Middle name: Kumar Last name: Kothari Age: 20
Reference solution
record = "AnKIT Kumar KOTHAri,20 "
parts = record.strip().split(",")
names = parts[0].title().split(" ")
age = int(parts[1])
print("First name:", names[0])
print("Middle name:", names[1])
print("Last name:", names[2])
print("Age:", age)
Chain methods left to right: record.strip().split(",") first trims the spaces, then splits the clean text.
Question 1 · Easy
email = "a.b@x.com". What does email.split("@")[0] give?
Question 2 · Medium
mobile = "9876543210". What is mobile[-4:]?
Question 3 · Hard
What does "ankit KOTHARI".title() give?
Key takeaways
Split text into parts, pick each part by its index, and clean it with a string method.
Save your progress
Start free and your progress, code and notes stay saved. Free for 1 month, no card needed.
Start free Log in