Module 5 · Beginner · Working with text

Python string practice: 15 problems

15 Python string practice problems with solutions: palindromes, anagrams, character counts, first unique character, compression and ciphers.

By theprogrammers team · · 7 min read

String questions are the most common type in Python coding tests for freshers. Campus placement online rounds, HackerRank tests and first technical interviews all lean on them, because text is easy to explain and quickly shows whether you can think in loops, dictionaries and string methods. These Python string practice problems with solutions cover the patterns that keep coming back.

The 15 problems go from easy to hard. Several have a "loop" answer and a "Pythonic" answer. Learn both: tests sometimes ban built-ins like [::-1] or Counter to see whether you understand what they do.

What you need first: Python strings, cleaning and splitting text and Python dictionaries. Problems 13 to 15 use regular expressions and Unicode code points.

Key terms

  • Palindrome: text that reads the same backwards, like "madam".
  • Anagram: two words with exactly the same letters in a different order, like "listen" and "silent".
  • Frequency count: how many times each item appears, usually stored in a dictionary.
  • collections.Counter: a ready-made dictionary for frequency counts, from Python's standard library.

Easy problems (1 to 5)

1. Reverse the string "Python".

Show the answer
text = "Python"
print(text[::-1])

reversed_text = ""
for ch in text:
    reversed_text = ch + reversed_text
print(reversed_text)
nohtyP
nohtyP

[::-1] is a slice with a step of −1, so it walks backwards. The loop puts each new character at the front.

2. Check whether "Never odd or even" is a palindrome, ignoring spaces and case.

Show the answer

Clean first, then compare with the reverse:

text = "Never odd or even"
clean = "".join(text.lower().split())
print(clean, clean == clean[::-1])
neveroddoreven True

For sentences with punctuation, keep only letters: "".join(ch for ch in text.lower() if ch.isalnum()).

3. Count how many times each character appears in "banana".

Show the answer
counts = {}
for ch in "banana":
    counts[ch] = counts.get(ch, 0) + 1
print(counts)

from collections import Counter
print(Counter("banana"))
{'b': 1, 'a': 3, 'n': 2}
Counter({'a': 3, 'n': 2, 'b': 1})

Counter lists the most common first when printed.

4. Capitalise the first letter of every word in "hello from pune" without using title().

Show the answer
text = "hello from pune"
words = [w[0].upper() + w[1:] for w in text.split()]
print(" ".join(words))
Hello From Pune

w[0].upper() + w[1:] leaves the rest of the word unchanged, unlike capitalize(), which lower-cases it.

5. Count the upper-case letters, lower-case letters, digits and spaces in "Hello World 2026".

Show the answer
text = "Hello World 2026"
upper = sum(ch.isupper() for ch in text)
lower = sum(ch.islower() for ch in text)
digits = sum(ch.isdigit() for ch in text)
spaces = text.count(" ")
print(upper, lower, digits, spaces)
2 8 4 2

Each is...() gives True or False, and sum counts the True values.

Medium problems (6 to 10)

6. Check whether "Listen" and "Silent" are anagrams.

Show the answer

Two ways: sort the letters, or compare letter counts.

from collections import Counter

a, b = "Listen", "Silent"
print(sorted(a.lower()) == sorted(b.lower()))
print(Counter(a.lower()) == Counter(b.lower()))
True
True

Sorting is O(n log n); counting is O(n). Both are fine for words. Comparing sets would be wrong: set("aab") == set("abb") is True, but they aren't anagrams.

7. Remove duplicate characters from "programming", keeping the first appearance of each.

Show the answer
text = "programming"
seen = set()
result = ""
for ch in text:
    if ch not in seen:
        seen.add(ch)
        result += ch
print(result)
print("".join(dict.fromkeys(text)))
progamin
progamin

dict.fromkeys keeps the first appearance of each key, in order.

8. Find the first character in "swiss" that doesn't repeat.

Show the answer

Count first, then walk the string in order and return the first character with a count of 1:

from collections import Counter

def first_unique(text):
    counts = Counter(text)
    for ch in text:
        if counts[ch] == 1:
            return ch
    return None

print(first_unique("swiss"), first_unique("aabb"))
w None

Two passes over the string is O(n). Calling text.count(ch) inside the loop would be O(n²).

9. Compress "aaabbcaaa" into "a3b2c1a3" (each run of a letter followed by its length).

Show the answer

Keep track of the current letter and how many times it has repeated. When the letter changes, write out the run:

def compress(text):
    if not text:
        return ""
    result = []
    current, count = text[0], 1
    for ch in text[1:]:
        if ch == current:
            count += 1
        else:
            result.append(f"{current}{count}")
            current, count = ch, 1
    result.append(f"{current}{count}")
    return "".join(result)

print(compress("aaabbcaaa"))
a3b2c1a3

The final append after the loop is easy to forget; without it, the last run is lost. Building a list and joining once is faster than += on a string in a long loop.

10. Find the longest word in "Data science needs patience".

Show the answer
sentence = "Data science needs patience"
print(max(sentence.split(), key=len))
patience

key=len tells max to compare the words by length. If two words tie, max returns the first one.

Hard problems (11 to 15)

11. Check whether a password is strong: at least 8 characters, with an upper-case letter, a lower-case letter and a digit. Test "Pune2026" and "pune2026".

Show the answer

any() stops at the first True, so each check is quick:

def is_strong(password):
    return (
        len(password) >= 8
        and any(ch.isupper() for ch in password)
        and any(ch.islower() for ch in password)
        and any(ch.isdigit() for ch in password)
    )

print(is_strong("Pune2026"), is_strong("pune2026"))
True False

12. Find the most common word in this text, ignoring case.

text = "The cat and the hat and THE bat"
Show the answer
from collections import Counter

text = "The cat and the hat and THE bat"
counts = Counter(text.lower().split())
print(counts.most_common(2))
[('the', 3), ('and', 2)]

most_common(n) returns the top n as (word, count) pairs.

13. Add up every number in "Paid 250 for food, 120 for auto and 45 for tea".

Show the answer
import re

text = "Paid 250 for food, 120 for auto and 45 for tea"
print(sum(int(n) for n in re.findall(r"\d+", text)))
415

Without regex, you can split on spaces and keep the pieces where piece.isdigit() is True, but that misses numbers stuck to punctuation, like "250,".

14. Encode "hello world" with a Caesar cipher that shifts each letter 3 places (a becomes d, x becomes a). Leave spaces alone.

Show the answer

Turn each letter into a number from 0 to 25, add the shift, wrap round with % 26, and turn it back:

def caesar(text, shift):
    result = []
    for ch in text:
        if ch.islower():
            result.append(chr((ord(ch) - ord("a") + shift) % 26 + ord("a")))
        else:
            result.append(ch)
    return "".join(result)

secret = caesar("hello world", 3)
print(secret)
print(caesar(secret, -3))
khoor zruog
hello world

ord("a") is 97. For "x": 120 − 97 = 23, plus 3 is 26, and 26 % 26 = 0, which is "a". A negative shift decodes.

15. Mask an email so only the first and last characters of the name show: "ahana.khan@gmail.com" becomes "a********n@gmail.com".

Show the answer
def mask_email(email):
    name, _, domain = email.partition("@")
    if len(name) <= 2:
        return "*" * len(name) + "@" + domain
    return name[0] + "*" * (len(name) - 2) + name[-1] + "@" + domain

print(mask_email("ahana.khan@gmail.com"))
print(mask_email("ab@x.com"))
a********n@gmail.com
**@x.com

"ahana.khan" has 10 characters, so 8 are hidden. Handling very short names separately avoids showing the whole name.

Interview questions

How do you check if two strings are anagrams in O(n) time?

Count the characters of both, with collections.Counter or a dictionary, and compare the counts. Sorting both strings also works but takes O(n log n).

Why is building a string with += in a loop slow, and what's the alternative?

Strings are immutable, so each += can create a new string and copy everything so far, which can make the loop O(n²). Appending pieces to a list and calling "".join(pieces) once is O(n).

How would you find the first non-repeating character in a string?

Count every character in one pass, then walk the string again and return the first character with a count of 1. That's O(n) time and O(k) extra space, where k is the number of different characters.

Key takeaways

  • Clean text before comparing: lower-case it and remove spaces or punctuation.
  • Frequency counts with a dictionary or Counter solve anagrams, duplicates and "first unique" problems.
  • Two passes (count, then check) beat a loop that calls count() inside another loop.
  • Build long strings in a list and join them once.
  • ord, chr and % 26 handle letter-shifting problems; re.findall extracts numbers from text.

Frequently asked questions

Can I use built-in functions in coding tests?

Usually yes, and using them well shows you know Python. Some lab exams and interviews ask you to avoid them to test your logic, so be ready to write the loop version too.

How should I practise string problems after these?

Try the easy string problems on HackerRank's Python track or LeetCode, where hidden tests check edge cases such as empty strings, one character and mixed case.

What edge cases should I test for string problems?

An empty string, a single character, all identical characters, mixed upper and lower case, spaces and punctuation, and non-English characters if the problem allows them.

What to learn next

  1. Start the functions module with variable scope and the LEGB rule.
  2. Revisit pattern matching in regular expressions in Python.
  3. See more interview-style problems in string problems: palindromes and anagrams.