Search code examples
pythonpython-3.xuppercaselowercase

python vowels to lowercase and consonants to uppercase


I'm new to python and I'm stuck on this particular exercise. I'm trying to make a program to take an input from the user (a string) and switch all the vowels to lowercase and consonants to uppercase.

Example input: "Learning python is fun."
Expected output: "LeaRNiNG PYTHoN iS FuN."

This is what I've tried:

def toggle(phrase):
    for letter in phrase:
        if letter not in "aeiou":
            letter = letter.upper()
        elif letter in "AEIOU":
            letter = letter.lower()
        else:
            letter = letter.upper()
    return phrase


print(toggle(input("Enter a phrase: ")))

However, the output is not toggling anything. What am I missing?


Solution

  • when you say letter = letter.upper, you're not actually changing the contents of the string phrase, you're just changing the string that the variable letter points to.

    In fact, you can't mutate strings in python. Try running "hello"[0] = "g" and you'll get an error.

    One solution is instead of trying to modify the string phrase, we can build a new string and put the correct letters in it. Here's what I mean:

    def toggle(phrase):
        answer = ""
        for letter in phrase:
            if letter not in "aeiouAEIOU":
                answer = answer + letter.upper()
            else:
                answer = answer + letter.lower()
        return answer
    
    
    print(toggle(input("Enter a phrase: ")))
    

    when you run this, you get

    Enter a phrase: Learning python is fun.
    LeaRNiNG PYTHoN iS FuN.
    

    It might look like I'm mutating the string when I say answer = answer + letter.upper(), but what actually happens is that, similar to what you did with letter, I'm not actually changing a string itself, I'm just making a new string (answer + letter.upper()) and assigning the value of that string to the variable answer. That's a subtle, but important difference.

    I also changed the way you decided whether to do uppercase or lowercase to make it work for lowercase vowels. The way you had it originally, if the current letter is "a", the else branch runs and it gets uppercased when it shouldn't. This is because "a" is in "aeiou" and it's not in "AEIOU", so the else branch runs and it gets uppercased.