Python Strings — Beginner Exercises

Learn the most common string operations in Python through practical exercises and solutions.

Exercise 1 Reverse a String

Given a string, return it backwards. This is one of the most classic string exercises and introduces you to Python's powerful slice notation.

The Quick Way — Slice with Step -1

Python slices accept a third parameter called the step. A step of -1 walks through the string from end to start, effectively reversing it.

python
# The quick way - slice with a step of -1
text = "hello"
reversed_text = text[::-1]   # "olleh"

The Manual Way — Loop and Build

This version shows what actually happens under the hood. Each character is prepended to the result, which naturally reverses the order.

python
def reverse_string(text):
    result = ""
    for char in text:
        result = char + result   # prepend each character
    return result

print(reverse_string("Python"))   # "nohtyP"
print(reverse_string(""))         # ""
Key Idea
[::-1] is the Pythonic shortcut for reversing any sequence. The manual loop shows the underlying logic — prepending builds the string in reverse.

Exercise 2 Count Vowels

Count how many vowels (a, e, i, o, u) appear in a string. This exercise practices iteration, conditionals, and the in keyword for membership testing.

python
def count_vowels(text):
    vowels = "aeiou"
    count = 0
    for char in text.lower():
        if char in vowels:
            count += 1
    return count

print(count_vowels("hello"))          # 2
print(count_vowels("AEIOU"))          # 5
print(count_vowels("rhythm"))         # 0
print(count_vowels("Beautiful Day"))  # 6
Key Idea
Convert to lowercase first with .lower() so you only need to check one case. The in keyword checks membership in any string or list.

Exercise 3 Check for a Palindrome

A palindrome reads the same forwards and backwards (e.g. "racecar"). This exercise combines string reversal with string cleaning.

Simple Version

python
def is_palindrome(text):
    cleaned = text.lower()
    return cleaned == cleaned[::-1]

print(is_palindrome("racecar"))   # True
print(is_palindrome("Madam"))     # True
print(is_palindrome("hello"))     # False

Strict Version — Ignoring Spaces & Punctuation

Real-world palindromes often contain spaces and punctuation. Use .isalnum() to keep only letters and digits.

python
def is_palindrome_strict(text):
    cleaned = ""
    for char in text.lower():
        if char.isalnum():          # letters and digits only
            cleaned += char
    return cleaned == cleaned[::-1]

print(is_palindrome_strict("A man, a plan, a canal: Panama"))  # True
Fragile — case-sensitive
"Madam" == "Madam"[::-1]
# "Madam" == "madaM" → False
Robust — normalize first
"Madam".lower() == "Madam".lower()[::-1]
# "madam" == "madam" → True
Key Idea
.isalnum() returns True for letters and digits — a handy way to strip out spaces and punctuation before comparison.

Exercise 4 Capitalize Each Word

Make the first letter of every word uppercase and the rest lowercase. This teaches you the split → transform → join pattern, one of the most useful patterns in string processing.

python
def capitalize_words(text):
    words = text.split()
    result = []
    for word in words:
        new_word = word[0].upper() + word[1:].lower()
        result.append(new_word)
    return " ".join(result)

print(capitalize_words("hello world"))     # "Hello World"
print(capitalize_words("LOUD NOISES"))     # "Loud Noises"
print(capitalize_words("python is fun"))   # "Python Is Fun"
Built-in shortcut: .title()

Python has a built-in method that does the same thing in one call:

python
print("hello world".title())   # "Hello World"

However, .title() can behave unexpectedly with apostrophes (e.g. "it's" becomes "It'S"), so knowing the manual approach is valuable.

Key Idea
.split() breaks a string into a list of words. " ".join() glues a list back into a single string with spaces. This split-transform-join pattern appears everywhere in Python.

Exercise 5 Count Word Frequency

Count how many times each word appears in a sentence. This introduces the fundamental dictionary counting pattern used throughout Python.

python
def word_frequency(text):
    words = text.lower().split()
    freq = {}
    for word in words:
        if word in freq:
            freq[word] += 1
        else:
            freq[word] = 1
    return freq

print(word_frequency("the cat sat on the mat"))
# {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
Common mistake — KeyError
freq[word] += 1
# KeyError if word not yet in dict!
Check first, then increment
if word in freq:
    freq[word] += 1
else:
    freq[word] = 1
Key Idea
Dictionaries are the standard way to count things in Python. The if key in dict / else pattern is one you will see everywhere.

Exercise 6 Remove Duplicate Characters

Keep only the first occurrence of each character in a string. This teaches the "seen set" tracking pattern.

python
def remove_duplicates(text):
    seen = ""
    result = ""
    for char in text:
        if char not in seen:
            seen += char
            result += char
    return result

print(remove_duplicates("aabbcc"))       # "abc"
print(remove_duplicates("hello world"))  # "helo wrd"
print(remove_duplicates("banana"))       # "ban"
Key Idea
Track what you have already seen. not in checks whether a character is missing from a string or list. This "seen" tracking pattern is useful for filtering duplicates in many contexts.

Exercise 7 Find the Longest Word

Return the longest word in a sentence. This combines splitting, iteration, and comparison.

python
def longest_word(text):
    words = text.split()
    longest = ""
    for word in words:
        if len(word) > len(longest):
            longest = word
    return longest

print(longest_word("I love programming"))      # "programming"
print(longest_word("the quick brown fox"))      # "quick"
print(longest_word("go do it"))                 # "go" (first match)
One-liner using max()
python
text = "I love programming"
print(max(text.split(), key=len))   # "programming"

max() with key=len tells Python to compare items by their length rather than alphabetically. This is a clean, idiomatic shortcut.

Key Idea
len() gives you the length of a string. max() with key=len is a clean shortcut for finding the longest item in a list.

Quick Reference — Common String Methods

These are the string methods you will reach for most often. Keep this as a handy cheat sheet.

python
s = "Hello, World!"

s.lower()            # "hello, world!"
s.upper()            # "HELLO, WORLD!"
s.strip()            # removes leading/trailing whitespace
s.replace("o","0")   # "Hell0, W0rld!"
s.startswith("He")  # True
s.endswith("!")      # True
s.find("World")      # 7  (index where it starts, -1 if not found)
s.count("l")         # 3
s.split(", ")        # ["Hello", "World!"]
", ".join(["a","b"]) # "a, b"
s.isdigit()          # False
s.isalpha()          # False (has comma and space)
s[0:5]               # "Hello"  (slicing)
len(s)               # 13

Summary — Key Takeaways

Exercise Core Concept Key Method / Syntax
Reverse a String Slice step parameter [::-1]
Count Vowels Membership testing in, .lower()
Palindrome Check String cleaning & comparison .isalnum(), [::-1]
Capitalize Words Split → Transform → Join .split(), " ".join()
Word Frequency Dictionary counting if key in dict
Remove Duplicates Seen-set tracking not in
Longest Word Comparison via length len(), max(key=len)