2

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")
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
Ruben
  • 23
  • 1
  • 1
  • 3
  • See [Deleting consonants from a string in Python](http://stackoverflow.com/questions/29998052/deleting-consonants-from-a-string-in-python) for a variety of useful techniques that can be applied to this problem. – PM 2Ring Sep 10 '16 at 13:27

5 Answers5

7

Something like this?

sentence = input('Enter your sentence: ' )
for letter in sentence:
    if letter in 'aeiou':
        print(letter)
user94559
  • 59,196
  • 6
  • 103
  • 103
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])
jedwards
  • 29,432
  • 3
  • 65
  • 92
1

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")
Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
0

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")
GarethPW
  • 399
  • 1
  • 3
  • 11
0

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)