Five Python Exercises for Working With Strings and Lists
Practice character classification, deduplication, index-based changes and run expansion with Python loops.
These five exercises show how Python loops translate simple rules into string and list transformations. The examples use the operations documented in Python’s data structures tutorial and string method reference.
Classify and deduplicate characters
Use separate filters for letters and digits. That makes it explicit what happens to punctuation. To remove duplicate characters while preserving their first occurrence, use an insertion-ordered dictionary.
sample = 'd4a2-c8'
letters = ''.join(ch for ch in sample if ch.isalpha())
digits = ''.join(ch for ch in sample if ch.isdigit())
print(letters + digits) # dac428
print(''.join(dict.fromkeys('banana'))) # banChange alternate list elements
enumerate() gives you each index and value. The examples apply the transformation at odd indices, which are the second, fourth and subsequent alternating positions.
words = ['ALPHA', 'BRAVO', 'CHARLIE', 'DELTA']
lowered = [word.lower() if i % 2 else word for i, word in enumerate(words)]
reversed_words = [word[::-1] if i % 2 else word for i, word in enumerate(words)]Expand character and count pairs
For inputs that contain one character followed by one decimal digit per pair, check the format before repeating characters. Counts with multiple digits require a different parser.
encoded = 'm2t3'
if len(encoded) % 2 or any(ch not in '0123456789' for ch in encoded[1::2]):
raise ValueError('Expected character and digit pairs')
decoded = ''.join(ch * int(count) for ch, count in zip(encoded[::2], encoded[1::2]))
print(decoded) # mmttt
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0