concept Bananas in category python

appears as: Banas
Tiny Python Projects: Learn coding and testing with puzzles and games

This is an excerpt from Manning's book Tiny Python Projects: Learn coding and testing with puzzles and games.

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:

#!/usr/bin/env python3
"""Apples and Bananas"""
 
import argparse
import os
 
 
# --------------------------------------------------
def get_args():
    """get command-line arguments"""
 
    parser = argparse.ArgumentParser(
        description='Apples and bananas',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
 
    parser.add_argument('text', metavar='text', help='Input text or file')  #1
 
    parser.add_argument('-v',
                        '--vowel',
                        help='The vowel(s) allowed',
                        metavar='vowel',
                        type=str,
                        default='a',
                        choices=list('aeiou'))                              #2
 
    args = parser.parse_args()
 
    if os.path.isfile(args.text):                                           #3
        args.text = open(args.text).read().rstrip()                         #4
 
    return args
 
 
# --------------------------------------------------
def main():
    """Make a jazz noise here"""
 
    args = get_args()
    text = args.text
    vowel = args.vowel
    new_text = []                                                           #5
 
    for char in text:                                                       #6
        if char in 'aeiou':                                                 #7
            new_text.append(vowel)                                          #8
        elif char in 'AEIOU':                                               #9
            new_text.append(vowel.upper())                                  #10
        else:
            new_text.append(char)                                           #11
 
    print(''.join(new_text))                                                #12
 
 
# --------------------------------------------------
if __name__ == '__main__':
    main()