String Exercises
Beginner Exercises
- Reverse a string without using slicing ([::-1])
- Count the number of vowels in a string
- Check if a string is a palindrome
- Convert a string to alternating case (e.g., HeLlO)
- Remove all spaces from a string
Example
# Example solution for vowel count
def count_vowels(text):
vowels = "aeiouAEIOU"
return sum(1 for char in text if char in vowels)
print(count_vowels("Hello World")) # 3
Output
3
Intermediate Challenges
Task | Input | Expected Output |
---|---|---|
Title case conversion | "hello world" | "Hello World" |
Find longest word | "Python is awesome" | "awesome" |
Password validator (min 8 chars, contains letters and numbers) | "Pass123" | False |
String compression (count consecutive chars) | "aaabbbcc" | "a3b3c2" |
Anagram check | "listen", "silent" | True |
Advanced Problems
Example
# Exercise: Implement Caesar Cipher encryption
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
result += chr((ord(char) - base + shift) % 26 + base)
else:
result += char
return result
# Test the function
print(caesar_cipher("Hello", 3)) # 'Khoor'
Output
Khoor
ℹ️ Note: Solutions should handle edge cases like empty strings, punctuation, and non-alphabetic characters.