python - code to figure out lowercase vowels, python question
问题描述
I have a question in my home work assignment, The user enters a string of all lowercase letters. The python program is suppose to tell them whether or not the string contains a lowercase vowel somewhere
, the problem I have is when i enter lets say more then letter I they all comeback wrong. Like if I enter (ab) it will come back saying all of there are no lower case vowels. If my text has at least one vowel, it should print "Contains a lowercase vowel!"
I added a picture to help show more
my OG code in case my picture does not load
x = input("Enter a string of lowercase letters: " )
c = ('a','e','i','o','u')
for c in x:
if x in (c):
print ("Contains a lowercase vowel!")
else:
print ("Doesn't contain a lowercase vowel.")
解决方案
在 Python 中有几种方法可以做到这一点。
所有方法都依赖于 Python 中的字符串是可迭代的这一事实(即,您可以循环遍历它们)。
给定这个字符串:
>>> st='xyzabc'
您可以使用 any 检查这些字符中的任何一个是否在字符串'aeiou'
中:
>>> any(c in 'aeiou' for c in st)
True
(any 函数内的部分是 Python理解——你需要用 Python 理解的东西)
您还可以使用集合交集:
>>> set('aeiou') & set(st)
{'a'}
或过滤的列表理解:
>>> [c for c in st if c in 'aeiou']
['a']