Search code examples
pythonpython-3.xstringlistlist-comprehension

Delete all vowels from a string using a list-comprehension


I'm trying to solve a challenge on Codewars.

Trolls are attacking your comment section!

A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.

Your task is to write a function that takes a string and return a new string with all vowels removed.

For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".

Note: for this kata y isn't considered a vowel.

This is working:

def disemvowel(string):
    output = []
    for char in string:
        if char not in "aeiouAEIOU":
            output.extend(char)
    return "".join(output)

But I want to do it in one line with a list comprehension. I tried this:

return "".join([[].extend(char) for char in string if char not in "aeiouAEIOU"])

... but I'm getting

TypeError: sequence item 0: expected str instance, NoneType found


Solution

  • You're trying to make a list within your list-comprehension; you can just use the existing list:

    return "".join([char for char in x if char not in "aeiouAEIOU"])
    

    Note that we could even omit the list comprehension and just use a generator expression (by omitting the square brackets), but join() works internally by converting the sequence to a list anyway, so in this case using a list-comprehension is actually quicker.