Print only vowels in a string

Question:

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")
Asked By: Ruben

||

Answers:

Something like this?

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

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")

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])
Answered By: jedwards

You could always use RegEx:

import re

sentence = input("Enter your sentence: ")
vowels = re.findall("[aeiou]",sentence.lower())

if len(vowels) == 0:
    for i in vowels:
        print(i)
else:
    print("Empty")
Answered By: GarethPW

You can always do this:

vowels = ['a', 'e', 'i', 'o', 'u', 'y']
characters_input = input('Type a sentence: ')
input_list = list(characters_input)
vowels_list = []
for x in input_list:
    if x.lower() in vowels:
        vowels_list.append(x)
vowels_string = ''.join(vowels_list)
print(vowels_string)

(I am also a beginner btw)

Answered By: Roberts

Try this:

sentence = input('nPlease enter your sentence: ')

for letter in sentence:
   if letter in ['a','e','i','o','u']:
       print('n',letter)
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.