Python practice

Python string practice questions

15 problems, ordered from easiest. They run in your browser, and 8 are free.

Start with Bigrams from a sentence

The idea in a minute

A string is text. Python can slice it, split it into pieces, change its case and search inside it, and most questions combine two or three of these.

The problems start with indexing and slicing and move to counting characters, checking palindromes and anagrams, and cleaning messy text.

Example: Count each letter

word = "banana"
counts = {}
for ch in word:
    counts[ch] = counts.get(ch, 0) + 1
print(counts)
print(word[::-1], word.upper(), word.count("an"))

What it prints

{'b': 1, 'a': 3, 'n': 2}
ananab BANANA 2

What to watch for

  • Strings cannot be changed in place. Every method returns a new string.
  • Indexing starts at 0, and a slice stops before its end number.
  • Use split() with no argument to split on any run of spaces.

Strings problems

  1. Bigrams from a sentencebeginner · Free
  2. Longest common prefixbeginner · Free
  3. Most common word in a support ticketbeginner · Free
  4. Reverse words in a log messagebeginner · Free
  5. Validate a discount code formatbeginner · Free
  6. Parse a delimited inventory linebeginner · Free
  7. Compact a run-length encoded event logbeginner · Free
  8. Expand a run-length encoded shift logbeginner · Free
  9. Top error codes from log linesintermediate · Locked
  10. Normalize a batch of phone numbersintermediate · Locked
  11. Match opening and closing tagsintermediate · Locked
  12. Parse a fixed-width mainframe extractintermediate · Locked
  13. Lazily read and filter a large log iteratorintermediate · Locked
  14. Safely parse a batch of numeric stringsintermediate · Locked
  15. Longest palindromic substringadvanced · Locked

Want a guided order across every topic? Open the practice sheets or the Python hub.