Python String handling: 14 practice problems
UNIT 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise String handling nowAll topicsTheory: String handling in Python
THEORY
------
* CREATING: 'single' "double" """triple (multi-line)""" str(42) "-" * 10
Escapes: \n newline \t tab \\ backslash \" quote. Raw string: r"C:\new" (no escapes)
* IMMUTABLE: s[0] = "x" -> TypeError. Every method returns a NEW string.
* INDEXING & SLICING s = "PYTHON"
index: P Y T H O N
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
s[0] -> "P" s[-1] -> "N" s[1:4] -> "YTH" (stop excluded) s[:2] -> "PY"
s[::2] -> "PTO" s[::-1] -> "NOHTYP" (reverse) slices never raise IndexError
* OPERATORS: + concat, * repeat, in substring test, == < > compare (lexicographic)
len(s), min(s), max(s), sorted(s) -> list of chars, ord("A") -> 65, chr(97) -> "a"
* METHODS (all return new values)
case upper lower title capitalize swapcase casefold
test isdigit isalpha isalnum isspace isupper islower startswith endswith isidentifier
search find (-1 if missing) index (ValueError) count rfind
change replace(old, new) strip/lstrip/rstrip(chars) zfill(5) center/ljust/rjust(w)
split split() on whitespace, split(",") on comma, splitlines(), partition(":")
join "-".join(["a", "b"]) -> "a-b" (join is called ON the separator)
* SORTING STRINGS: "".join(sorted("banana")) -> "aaabnn"
sorted(words, key=str.lower) case-insensitive sorted(words, key=len) by length
Uppercase sorts BEFORE lowercase ("Z" < "a") because ord("Z") = 90 < ord("a") = 97.
* FORMATTING
f"{name}" f"{x:.2f}" f"{n:5d}" f"{s:<10}" left f"{s:>10}" right f"{s:^10}" centre
f"{n:,}" -> 1,234,567 f"{0.25:.0%}" -> 25% f"{n:08.3f}" f"{n:b}" binary
"{} is {}".format(a, b) "%s is %d" % (a, b) (older styles)
* Building strings in a loop: collect pieces in a LIST then "".join(list) — faster than +=.
14 String handling practice problems
1. Mask a Phone Number — loop over chars + counting
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. '+** ***** *3210'. Use `return`, not print().
Real world: Banking apps show only the last 4 digits of your phone number.
Replace every DIGIT except the LAST 4 DIGITS with '*'. Non-digits (+, spaces) stay.
mask_phone("+91 98765 43210") -> "+** ***** *3210"
mask_phone("1234") -> "1234"
Solve “Mask a Phone Number — loop over chars + counting” in your browser →2. Reverse Word Order (LeetCode 151)
Easy3 ways to solve📤 OUTPUT: return a str (text), e.g. 'blue is sky the'. Use `return`, not print().
Words separated by any amount of whitespace; output single-spaced, no leading/trailing spaces.
reverse_words(" the sky is blue ") -> "blue is sky the"
Solve “Reverse Word Order (LeetCode 151)” in your browser →3. Anagram Check (LeetCode 242) — sorting strings
Easy3 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Ignore case and spaces. is_anagram("Dormitory", "dirty room") -> True
Ways: compare sorted strings · count characters with a dict
Solve “Anagram Check (LeetCode 242) — sorting strings” in your browser →4. Run-Length Encoding — loop with a counter
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'a3b1c2d4'. Use `return`, not print().
Real world: Simple image/fax compression stores "aaab" as "a3b1".
compress("aaabccdddd") -> "a3b1c2d4" compress("") -> ""
Solve “Run-Length Encoding — loop with a counter” in your browser →5. Character Statistics — str test methods
Easy2 ways to solve📤 OUTPUT: return a tuple, e.g. (5, 1, 2, 1). Use `return`, not print().
Return a tuple (letters, digits, spaces, others).
char_types("Hi 2 you!") -> (5, 1, 2, 1)
Solve “Character Statistics — str test methods” in your browser →6. Receipt Printer — format specs
Easy3 ways to solve📤 OUTPUT: return a str (text), e.g. 'Milk 2 x 45.50'. Use `return`, not print().
Item left-aligned in 10 chars, qty right-aligned in 3, " x ", price right-aligned width 8 with 2 decimals.
receipt_line("Milk", 2, 45.5) -> "Milk 2 x 45.50"
Solve “Receipt Printer — format specs” in your browser →7. Caesar Cipher — ord/chr + modulo
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'Khoor, Zruog!'. Use `return`, not print().
Real world: The oldest encryption: shift each letter by `shift` (wrap around z->a).
Keep case; leave non-letters unchanged. shift may be negative (decrypt).
caesar("Hello, World!", 3) -> "Khoor, Zruog!" caesar("abc", -1) -> "zab"
Solve “Caesar Cipher — ord/chr + modulo” in your browser →8. Signup Password Validator
Medium2 ways to solve📤 OUTPUT: return a list, e.g. ['length', 'upper', 'digit', 'special']. Use `return`, not print().
Return a list of the rules FAILED, in this order (empty list = strong):
"length" (< 8 chars), "upper" (no uppercase), "lower" (no lowercase),
"digit" (no digit), "special" (none of !@#$%^&*)
password_strength("abc") -> ["length", "upper", "digit", "special"]
password_strength("Str0ng!Pass") -> []
Ways: any(ch.isupper() for ch in pw) · one loop setting flags
Solve “Signup Password Validator” in your browser →9. Extract Email Domain — split / partition / find
Easy3 ways to solve📤 OUTPUT: return a str (text), e.g. 'mail.google.com'. Use `return`, not print().
Return the part after "@". If there isn't EXACTLY one "@", return "".
email_domain("user@mail.google.com") -> "mail.google.com" email_domain("bad.com") -> ""
Solve “Extract Email Domain — split / partition / find” in your browser →10. Sort Words Alphabetically (case-insensitive) — return them joined by single spaces.
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. 'Apple apple banana cherry'. Use `return`, not print().
sort_words("banana Apple cherry apple") -> "Apple apple banana cherry"
(sorted is STABLE: equal keys keep their original order)
Solve “Sort Words Alphabetically (case-insensitive) — return them joined by single spaces.” in your browser →11. Blog URL Slug
Medium2 ways to solve📤 OUTPUT: return a str (text), e.g. 'hello-world-python-3'. Use `return`, not print().
Real world: "Hello, World! Python 3" becomes the URL /hello-world-python-3
Lowercase; keep letters/digits; any run of other characters becomes ONE "-"; no "-" at the ends.
slugify("Hello, World! Python 3") -> "hello-world-python-3"
slugify(" --AI & ML-- ") -> "ai-ml"
Solve “Blog URL Slug” in your browser →12. Overlapping Substring Count — viva gotcha
Medium3 ways to solve📤 OUTPUT: return an int, e.g. 3. Use `return`, not print().
"aaaa".count("aa") is 2, but "aa" actually appears at positions 0, 1, 2.
Return the overlapping count. count_overlapping("aaaa", "aa") -> 3
Ways: loop i over positions with slicing · repeated find(sub, i + 1)
Solve “Overlapping Substring Count — viva gotcha” in your browser →13. Support-Ticket Redactor — interview at a customer-support SaaS company
Project1 way to solve📤 OUTPUT: return a str (text), e.g. "Hi, I'm [EMAIL] and my card **** **** **** 12…. Use `return`, not print().
Interviewer: "Tickets must never store personal data. Redact it before saving."
* card numbers: 16 digits in groups of 4, separated by spaces, dashes or nothing
-> "**** **** **** 1234" (keep the last 4) (do cards BEFORE phones)
* phone numbers: 10 digits, optionally prefixed with +91 and a space or dash -> "[PHONE]"
* emails: name@domain.tld -> "[EMAIL]"
* finally collapse every run of whitespace to one space and strip the ends.
Regex (re.sub) is allowed and recommended.
Solve “Support-Ticket Redactor — interview at a customer-support SaaS company” in your browser →14. Stage 7 — Pretty Error Messages (what makes a compiler friendly)
Compiler1 way to solve📤 OUTPUT: return a str (text), e.g. "Line 3: x = 5 +* 2\n ^\nSyntaxE…. Use `return`, not print().
Return 3 lines joined with "
":
Line 3: x = 5 +* 2
^ <- the ^ sits under character `col` (0-based) of line_text
SyntaxError: unexpected '*'
The caret line is spaces + "^" (account for the "Line N: " prefix).
Solve “Stage 7 — Pretty Error Messages (what makes a compiler friendly)” in your browser →