Print only vowels in a string

29,098

Solution 1

Something like this?

sentence = input('Enter your sentence: ' )
for letter in sentence:
    if letter in 'aeiou':
        print(letter)

Solution 2

The two answers are good if you want to print all the occurrences of the vowels in the sentence -- so "Hello World" would print 'o' twice, etc.

If you only care about distinct vowels, you can instead loop over the vowels. In a sense, you're flipping the code suggested by the other answers:

sentence = input('Enter your sentence: ')

for vowel in 'aeiou':
    if vowel in sentence:
        print(vowel)

So, "Hey there, everything alright?" would print

a e i

As opposed to:

e e e e e i a i

And the same idea, but following Jim's method of unpacking a list comprehension to print:

print(*[v for v in 'aeiou' if v in sentence])

Solution 3

Supply provide an a list comprehension to print and unpack it:

>>> s = "Hey there, everything allright?" # received from input
>>> print(*[i for i in s if i in 'aeiou'])
e e e e e i a i

This makes a list of all vowels and supplies it as positional arguments to the print call by unpacking *.

If you need distinct vowels, just supply a set comprehension:

print(*{i for i in s if i in 'aeiou'}) # prints i e a

If you need to add the else clause that prints, pre-construct the list and act on it according to if it's empty or not:

r = [i for i in s if i in 'aeiou']  
if r:
   print(*r)
else:
   print("empty")
Share:
29,098
Ruben
Author by

Ruben

Updated on July 01, 2020

Comments

  • Ruben
    Ruben almost 4 years

    I am new in Python and I'm trying to print all the vowels in a string. So if someone enters "Hey there, everything alright?" , all vowels needs to be printed...but I don't know how? (so it's not about counting the vowels, its about printing the vowels)

    For now I've got this ;

    sentence = input('Enter your sentence: ' )
    
    if 'a,e,i,o,u' in sentence:
        print(???)
    
    else:
        print("empty")