Learn the most common string operations in Python through practical exercises and solutions.
Given a string, return it backwards. This is one of the most classic string exercises and introduces you to Python's powerful slice notation.
Python slices accept a third parameter called the step. A step of -1 walks through the string from end to start, effectively reversing it.
# The quick way - slice with a step of -1 text = "hello" reversed_text = text[::-1] # "olleh"
This version shows what actually happens under the hood. Each character is prepended to the result, which naturally reverses the order.
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("")) # ""
[::-1] is the Pythonic shortcut for reversing any sequence. The manual loop shows the underlying logic — prepending builds the string in reverse.
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.
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
.lower() so you only need to check one case. The in keyword checks membership in any string or list.
A palindrome reads the same forwards and backwards (e.g. "racecar"). This exercise combines string reversal with string cleaning.
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
Real-world palindromes often contain spaces and punctuation. Use .isalnum() to keep only letters and digits.
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
"Madam" == "Madam"[::-1] # "Madam" == "madaM" → False
"Madam".lower() == "Madam".lower()[::-1] # "madam" == "madam" → True
.isalnum() returns True for letters and digits — a handy way to strip out spaces and punctuation before comparison.
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.
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"
.title()
▼
Python has a built-in method that does the same thing in one call:
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.
.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.
Count how many times each word appears in a sentence. This introduces the fundamental dictionary counting pattern used throughout 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}
freq[word] += 1 # KeyError if word not yet in dict!
if word in freq: freq[word] += 1 else: freq[word] = 1
if key in dict / else pattern is one you will see everywhere.
Keep only the first occurrence of each character in a string. This teaches the "seen set" tracking pattern.
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"
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.
Return the longest word in a sentence. This combines splitting, iteration, and comparison.
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)
max()
▼
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.
len() gives you the length of a string. max() with key=len is a clean shortcut for finding the longest item in a list.
These are the string methods you will reach for most often. Keep this as a handy cheat sheet.
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
| 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) |