Reputation: 47
s = raw_input("string: ")
if ("a", "e", "i", "o", "u") in s:
print s.count("a", "e", "i", "o", "u")
else:
print ("No vowels")
this is my code, essentially i want someone to type in a string and for this program to count the amount of vowels. Why doesnt this work?
Upvotes: 1
Views: 14027
Reputation: 63709
Here is a snippet using Python's built-in sum
, which relies on Python's equivalence of True and 1:
>>> s = "sldkjfwoqpwefjsfueiof"
>>> num_vowels = sum(c in "aeiou" for c in s.lower())
>>> print num_vowels
6
For every character in s, evaluate whether it is in "aeiou" or not. If it is, this evaluates to True, equivalent to the value 1. Characters not in "aeiou" evaluate to False, equivalent to 0. sum
adds these all up, the result will tell you how many characters in the input string satisfy the vowel condition. (Don't forget to convert the input string to lower case as shown by calling .lower()
, else you will accidentally skip over vowels that are capitalized.)
Upvotes: 1
Reputation: 2419
Your code checks if a tuple ("a", "e", "i", "o", "u")
is inside string s
which of course is not existed.
If you need keep track of what vowel has been repeated how many times, you should do like this:
In[22]: s = 'aiuo hohoho'
In[23]: vowel_count = {i:s.count(i) for i in 'aiueo'}
In[24]: vowel_count
Out[24]: {'a': 1, 'e': 0, 'i': 1, 'o': 4, 'u': 1}
It gives you a dict of vowel:counts
, so you can get the count of any vowel like this:
In[25]: vowel_count['o']
Out[25]: 4
Upvotes: 2
Reputation: 16309
I bet it's trying to see if the tuple, ('a','e'...) is in the string, not the items individually. Iterate:
count = 0
for letter in 'aeiou':
if letter in s:
count += s.count(letter)
print count
Upvotes: 3
Reputation: 4912
You can do it in this way. Every element in the final list is the count of vowels you want.
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Take this for an example
a = 'aeiouaeioujjj'
print [a.count(item) for item in 'aeiou']
OUTPUT:
[2, 2, 2, 2, 2]
Upvotes: 1
Reputation: 3782
Or you can use a dict to remember the count of vowels:
s = raw_input("string: ")
aeiou_dict = {'a':0,'e':0,'i':0,'o':0,'u':0}
for char in s:
if char in 'aeiou':
aeiou_dict[char] += 1
else:
pass
print aeiou_dict
Upvotes: 1