Python List Comprehension | Sololearn: Learn to code for FREE!


Python List Comprehension

Code should output only consonants< I managed to omit only 'a', want to omit other vowels too (e,i,u etc) but doesn't work --> I tried like this ...if letter != 'a', 'u','e' Help me what I am doing wrong? word = input() print([letter for letter in word if letter != 'a'])

6/9/2021 6:23:44 PM

Dee Lingua

2 Answers

New Answer


Adilet Kambarov , you are very close to get it. instead of using the current if clause inside the comprehension, you can use this one: print([ ......if letter not in 'aeiou ']) this results in a list of single letters. so all vowels and spaces will not be in the output. if punctuation also should be excluded, put them also to the string with the vowels. a collection of punctuation characters can be get after importing module string. using "string.punctuation" gives you all these characters. so finally it could look like: print([.....if letter not in 'aeiou ' + string.punctuation])


# with regular expression that's quite easy: import re regex = re.compile("[^b-df-hj-np-tv-z]",re.I) new_text = re.sub(regex, "", text) # and if you want to only remove vowels, just change regex: regex = re.compile("[aeiou]",re.I)