Declarative programming describes what to find or transform and delegates the execution work to a tool. Regular expressions illustrate the contrast: a pattern states what text to match, while the regex engine determines whether it is found. section 14.5 section 8.3.2
Recognize the approach through these contrasts:
- Describe vowels with the pattern '[aeiou]' instead of iterating through characters and writing the matching logic manually. section 8.3.2
- Let re.sub() apply a declared replacement to matching text, including separate patterns for lowercase and uppercase vowels. section 8.3.2
- Treat list comprehensions, filter(), and map() as more concise ways to express selection or transformation over iterables. section 14.5
Replacing vowels with a pattern
pattern = '[aeiou]' vowel = 'o' re.sub(pattern, vowel, 'Apples and bananas!') # 'Applos ond bononos!' The program declares the characters to replace; re.sub() performs the search and replacement. section 8.3.2 section 14.0
>>> text = 'Apples and Bananas!' #1 >>> vowel = 'o' #2 >>> new_text = [] #3 >>> for char in text: #4 ... if char in 'aeiou': #5 ... new_text.append(vowel) #5 ... elif char in 'AEIOU': #6 ... new_text.append(vowel.upper()) #6 ... else: ... new_text.append(char) #7 ... >>> text = ''.join(new_text) #8 >>> text 'Opplos ond Bononos!'
Compare a character-by-character imperative vowel replacement with the declarative regex formulation. section 8.3.2













