8 Apples and Bananas: Find and replace

 

Have you ever misspelled a word? I haven’t, but I’ve heard that many other people often do. We can use computers to find and replace all instances of a misspelled word with the correction. Or maybe you’d like to replace all mentions of your ex’s name in your poetry with your new love’s name? Find and replace is your friend.


To get us started, let’s consider the children’s song “Apples and Bananas,” wherein we intone our favorite fruits to consume:

I like to eat, eat, eat apples and bananas

Subsequent verses substitute the main vowel sound in the fruits for various other vowel sounds, such as the long “a” sound (as in “hay”):

I like to ate, ate, ate ay-ples and ba-nay-nays

Or the ever-popular long “e” (as in “knee”):

I like to eat, eat, eat ee-ples and bee-nee-nees

And so forth. In this exercise, we’ll write a Python program called apples.py that takes some text, given as a single positional argument, and replaces all the vowels in the text with the given -v or --vowel options (with the default being a).

The program should be written in the 08_apples_and_bananas directory and should handle text on the command line:

$ ./apples.py foo
faa

And accept the -v or --vowel option:

$ ./apples.py foo -v i
fii

Your program should preserve the case of the input vowels:

$ ./apples.py -v i "APPLES AND BANANAS"
IPPLIS IND BININIS

As with the Howler program in chapter 5, the text argument may name a file, in which case your program should read the contents of the file:

8.1 Altering strings

8.1.1 Using the str.replace() method

8.1.2 Using str.translate()

8.1.3 Other ways to mutate strings

8.2 Solution

8.3 Discussion

8.3.1 Defining the parameters

8.3.2 Eight ways to replace the vowels

sitemap