Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcb123
Courses Plus Student 9,858 PointsWhat is optimal way of solving disemvowel?
I did complete the disemvowel challenge by using loop (v in vowels) within a loop of (w in word) to iterate, then reconstructed a new word (new_word += w) from characters where w == v did not occur.
Is there a more efficient way?
1 Answer
Manish Giri
16,266 PointsYou could use List Comprehension and the .join()
function to first create a list that does not have the vowels, then use .join()
to create a string from the list -
def disemvowel(word):
vowels = ["a", "e", "i", "o", "u"]
return "".join(w for w in word if w.lower() not in vowels)
If I break it down -
-
w for w in word
basically gives you all the letters inword
, becauseword
being astr
object is iterable. - the condition
if w.lower() not in vowels
is a containment check - it checks if the current letter is not a vowel, and if it isn't, it is returned in the list. - The final list is joined to form a string using
.join()
.
cb123
Courses Plus Student 9,858 Pointscb123
Courses Plus Student 9,858 Pointsvery nice. I did not realize that you could write python in this way. Hopefully this approach will be presented in future instructions. Thanks.