Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exchange vowels from user input in python

I want to have the user input a sentence and have the program print out the same sentence except having the vowels swapped as follows:

  • A = E
  • E = I
  • I = O
  • O = U
  • U = A

I have started writing the following code, but is there a more efficient way to do this other than telling the program what to do for every single letter?

inp = input("Enter a sentence: ")
for letter in inp:
    if letter == "a":
        print("e", end = "")
    if letter == "b":
        print("b", end = "")
    if letter == "c":
        print("c", end = "")
    if letter == "d":
        print("d", end = "")
    if letter == "e":
        print("i", end = "")
    if letter == "f":
        print("f", end = "")
    if letter == "g":
        print("g", end = "")
    if letter == "i":
        print("o", end = "")
    if letter == "o":
        print("u", end = "")
    if letter == "u":
        print("a", end = "")
like image 449
Mason Clarke Avatar asked Apr 20 '26 13:04

Mason Clarke


2 Answers

Probably the most efficient way would be using str.translate (with str.maketrans):

>>> inp = input("Enter a sentence: ")
>>> print(inp.translate(str.maketrans('AaEeIiOoUu', 'EeIiOoUuAa')))
Enter a sentence: hello YOU
Hillu YUA

But if you want to keep away from the str-methods you could use a dict instead of all these ifs:

change = {'A': 'E', 'a': 'e',
          'E': 'I', 'e': 'i',
          'I': 'O', 'i': 'o',
          'O': 'U', 'o': 'u',
          'U': 'A', 'u': 'a'}

for char in inp:
    print(change.get(char, char), end='')

This looks up if the character is in the change dictionary and if it is contained it prints it's value, otherwise the default (the second argument for .get - the original char) is printed.

like image 161
MSeifert Avatar answered Apr 23 '26 03:04

MSeifert


One of the fastest and easiest ways to achieve this is using a dictionary.

Create a dictionary where keys are the characters to remove, and the values are the characters to insert:

characters_to_swap = {'a':'e', 'e':'i', 'i':'o', 'o':'u', 'u':'a'}

Then iterate over the input:

data = input()
for character in data:
    if character in characters_to_swap:
        print(characters_to_swap[character], end='')
    else:
        print(character, end='')

Don't worry too much about the end parameter in print, it just corresponds to the last character printed. I set it to '' so it does not print a newline.

like image 34
Right leg Avatar answered Apr 23 '26 02:04

Right leg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!