Reputation: 23
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")
Upvotes: 2
Views: 42143
Reputation: 1
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)
Upvotes: 0
Reputation: 160557
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")
Upvotes: 1
Reputation: 408
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")
Upvotes: 0
Reputation: 30230
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])
Upvotes: 2
Reputation: 60143
Something like this?
sentence = input('Enter your sentence: ' )
for letter in sentence:
if letter in 'aeiou':
print(letter)
Upvotes: 7