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 us consider the children’s song "Apples and Bananas" wherein we intone about 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" (as in "hay") sound:

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 takes some text given as a single positional argument and replaces all the vowels in the text with a given -v or --vowel options (default a).

The program should handle text on the command line:

$ ./apples.py foo
faa

And accept the -v or --vowel option:

$ ./apples.py foo -v i
fii

You program should preserve the case of the input vowels:

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

As with the "Howler" program, 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 str.replace

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.4  Eight ways to replace the vowels

8.4.1  Method 1: Iterate every character

8.4.2  Method 2: Using str.replace