Print only vowels in a string

只谈情不闲聊 提交于 2019-12-24 03:51:48

问题


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

回答1:


Something like this?

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



回答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])



回答3:


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



回答4:


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



回答5:


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)



来源:https://stackoverflow.com/questions/39426149/print-only-vowels-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!