Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Lists Disemvowel

Help with this for loop.

def disemvowel(word): vowels = 'aeiouAEIOU' result = '' for letter in word: if letter in vowels: result = word.replace(letter, '') return result

I'm losing my sanity with this one?

it will proof when passed 'here' but when passed something like 'placeit' , no good?

can anyone explain this to me?

disemvowel.py
def disemvowel(word):
    vowels = 'aeiou'
    result = ''
    for letter in word:
        if letter in vowels:
            result = word.replace(letter, '')
            return result

1 Answer

Maurice Abney
PLUS
Maurice Abney
Courses Plus Student 9,847 Points

The trick to this solution lies in the fact that strings are immutable(cant change) but lists are mutable(ie, do work on list and then convert to string). What's being returned from each of your replace() calls is a new string acting on the original word, its not updated at all, so your end result will simply be the original word with the 'a's removed, e's i's o's and u's intact. reason being, after the first replace, the result is returned. A similar solution could be done with recursion by calling returning disemvowel(result) and changing a few lines but that's another discussion. You dont need recursion to solve this problem.

Here's my solution:

def disemvowel(word):
    result = [] # empty list
    for letter in word:
        if letter.lower()  not in "aeiou":
            result.append(letter)
    return ''.join(result) #join list back into string

Thank you very much, i had tried this prior to coming up with what is posted however, in the last line of code tried to use str(result) instead of ''.join() > joining the list into a string which did not work. I really like the sound of this recursion technique though, thank you for pointing that out. Always worth finding more than one way to do something.