I have a homework question which asks to read a string through raw input and count how many vowels are in the string. This is what I have so far but I have encountered a problem:
def vowels():
vowels = ["a","e","i","o","u"]
count = 0
string = raw_input ("Enter a string: ")
for i in range(0, len(string)):
if string[i] == vowels[i]:
count = count+1
print count
vowels()
It counts the vowels fine, but due to if string[i] == vowels[i]:, it will only count one vowel once as i keeps increasing in the range. How can I change this code to check the inputted string for vowels without encountering this problem?
inoperatorYou probably want to use the
inoperator instead of the==operator – theinoperator lets you check to see if a particular item is in a sequence/set.Some other comments:
Sets
The
inoperator is most efficient when used with aset, which is a data type specifically designed to be quick for “is item X part of this set of items” kind of operations.**
dicts are also efficient within, which checks to see if a key exists in the dict.Iterating on strings
A string is a sequence type in Python, which means that you don’t need to go to all of the effort of getting the length and then using indices – you can just iterate over the string and you’ll get each character in turn:
E.g.:
Initializing a set with a string
Above, you may have noticed that creating a set with pre-set values (at least in Python 2.x) involves using a list. This is because the
set()type constructor takes a sequence of items. You may also notice that in the previous section, I mentioned that strings are sequences in Python – sequences of characters.What this means is that if you want a set of characters, you can actually just pass a string of those characters to the
set()constructor – you don’t need to have a list one single-character strings. In other words, the following two lines are equivalent:Neat, huh? 🙂 Do note, however, that this can also bite you if you’re trying to make a set of strings, rather than a set of characters. For instance, the following two lines are not the same:
The former is a set with one element:
Whereas the latter is a set with three elements (each one a character):
Case sensitivity
Comparing characters is case sensitive.
'a' == 'A'is False, as is'A' in 'aeiou'. To get around this, you can transform your input to match the case of what you’re comparing against: