Reputation: 1
I am just starting to learn python right now and I came across this exercise. I found a way to do it but I don't think that it's the best way. This is what I have right now.
big_string = input("Enter a string of lowercase letters: ")
if "a" in big_string or "e" in big_string or "i" in big_string or "o" in big_string or "u" in big_string:
print "Contains a lowercase vowel!"
else:
print "Doesn't contain a lowercase vowel"
Is there a better way to do the if/in line?
Upvotes: 0
Views: 46
Reputation: 1686
Here's a one-liner for a slightly different kind if answer:
print("Contains a lowercase vowel!" if any(vowel in bigstring for vowel in ['a', 'e', 'i', 'o', 'u'])
else "Doesn't contain a lowercase vowel")
Upvotes: 0
Reputation: 951
big_string = raw_input("Enter a string of lowercase letters: ")
chars = set('aeiou')
if any((c in chars) for c in big_string):
print("Contains a lowercase vowel!")
else:
print("Doesn't contain a lowercase vowel")
Upvotes: 0
Reputation: 1140
You can use any(x in b for x in a)
to determine if any of the items in list a are in list b.
In your case, you can do something like this:
if any(x in big_string for x in ["a", "e", "i", "o", "u"]):
Upvotes: 0
Reputation: 155343
Without skipping straight to regexes, you could do:
if any(vowel in big_string for vowel in "aeiou"):
That said, it might be more expensive to scan a huge string five times than to do so once with a regex, so consider a regex here:
import re
...
if re.search(r'[aeiou]', big_string):
Upvotes: 2
Reputation: 660
How about this?
if any((c in big_string) for c in ['a', 'e', 'i', 'o', 'u']):
...
Upvotes: 0