17

I'm trying to count how many occurrences there are of specific characters in a string, but the output is wrong.

Here is my code:

inputString = str(input("Please type a sentence: "))
a = "a"
A = "A"
e = "e"
E = "E"
i = "i"
I = "I"
o = "o"
O = "O"
u = "u"
U = "U"
acount = 0
ecount = 0
icount = 0
ocount = 0
ucount = 0

if A or a in stri :
     acount = acount + 1

if E or e in stri :
     ecount = ecount + 1

if I or i in stri :
    icount = icount + 1

if o or O in stri :
     ocount = ocount + 1

if u or U in stri :
     ucount = ucount + 1

print(acount, ecount, icount, ocount, ucount)

If I enter the letter A the output would be: 1 1 1 1 1

RyPeck
  • 7,830
  • 3
  • 38
  • 58
user2975192
  • 317
  • 2
  • 6
  • 18
  • Where is `stri` declared? How are you generating the output? What's the input? – Thomas Upton Nov 14 '13 at 00:07
  • 1
    To count characters is a string use the count method: `'aabccc'.count('c')` – dawg Nov 14 '13 at 00:07
  • possible duplicate of [Count the amount of vowels in a sentence and display the most frequent](http://stackoverflow.com/questions/19933875/count-the-amount-of-vowels-in-a-sentence-and-display-the-most-frequent) – inspectorG4dget Nov 14 '13 at 00:08
  • 1
    You forgot `y`. – beruic Oct 08 '19 at 08:06
  • Does this answer your question? [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – Tomerikoo Jun 13 '20 at 19:32

29 Answers29

26

What you want can be done quite simply like so:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>

In case you don't know them, here is a reference on map and one on the *.

Community
  • 1
  • 1
17
def countvowels(string):
    num_vowels=0
    for char in string:
        if char in "aeiouAEIOU":
           num_vowels = num_vowels+1
    return num_vowels

(remember the spacing s)

philant
  • 34,748
  • 11
  • 69
  • 112
hanish
  • 171
  • 1
  • 2
10
>>> sentence = input("Sentence: ")
Sentence: this is a sentence
>>> counts = {i:0 for i in 'aeiouAEIOU'}
>>> for char in sentence:
...   if char in counts:
...     counts[char] += 1
... 
>>> for k,v in counts.items():
...   print(k, v)
... 
a 1
e 3
u 0
U 0
O 0
i 2
E 0
o 0
A 0
I 0
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 4
    Rather than `counts = {i:0 for i in 'aeiouAEIOU'}` you can do `counts={}.fromkeys('aeiouAEIOU',0)` – dawg Nov 14 '13 at 00:10
10
data = str(input("Please type a sentence: "))
vowels = "aeiou"
for v in vowels:
    print(v, data.lower().count(v))
kyle k
  • 5,134
  • 10
  • 31
  • 45
6

Use a Counter

>>> from collections import Counter
>>> c = Counter('gallahad')
>>> print c
Counter({'a': 3, 'l': 2, 'h': 1, 'g': 1, 'd': 1})
>>> c['a']    # count of "a" characters
3

Counter is only available in Python 2.7+. A solution that should work on Python 2.5 would utilize defaultdict

>>> from collections import defaultdict
>>> d = defaultdict(int)
>>> for c in s:
...     d[c] = d[c] + 1
... 
>>> print dict(d)
{'a': 3, 'h': 1, 'l': 2, 'g': 1, 'd': 1}
Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
5

if A or a in stri means if A or (a in stri) which is if True or (a in stri) which is always True, and same for each of your if statements.

What you wanted to say is if A in stri or a in stri.

This is your mistake. Not the only one - you are not really counting vowels, since you only check if string contains them once.

The other issue is that your code is far from being the best way of doing it, please see, for example, this: Count vowels from raw input. You'll find a few nice solutions there, which can easily be adopted for your particular case. I think if you go in detail through the first answer, you'll be able to rewrite your code in a correct way.

Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109
5

For anyone who looking the most simple solution, here's the one

vowel = ['a', 'e', 'i', 'o', 'u']
Sentence = input("Enter a phrase: ")
count = 0
for letter in Sentence:
    if letter in vowel:
        count += 1
print(count)
Georgy
  • 12,464
  • 7
  • 65
  • 73
Keith lam
  • 51
  • 1
  • 2
  • you should do "if letter.lower() in vowel" to consider also the upper case vowels – Nan Jun 13 '20 at 19:52
  • That's not the simplest. This is: `count = len(re.findall('[aeiouAEIOU]', Sentence))`. But the question wants an individual count for each letter so neither solution is correct. – Mark Ransom May 16 '21 at 03:23
4

Another solution with list comprehension:

vowels = ["a", "e", "i", "o", "u"]

def vowel_counter(str):
  return len([char for char in str if char in vowels])

print(vowel_counter("abracadabra"))
# 5
lendoo
  • 332
  • 4
  • 5
3
>>> string = "aswdrtio"
>>> [string.lower().count(x) for x in "aeiou"]
[1, 0, 1, 1, 0]
  • Counts the number of occurrences of each vowel in the 'string' and puts them in a list i.e. [1a, 0e, 1i, 1o, 0u]. lower() changes the 'string' to lowercase so it will also count uppercase vowels if there were any. – david clark Nov 25 '17 at 04:21
2
count = 0 

string = raw_input("Type a sentence and I will count the vowels!").lower()

for char in string:

    if char in 'aeiou':

        count += 1

print count
  • You could go through `string.lower()` instead of just iterating through the plain input string, as it seems OP wants to be able to deal with uppercase letters. Also, your test for a vowel could just be `if char in "aeiou":`. – Efferalgan Oct 07 '16 at 19:00
  • Great advice. Thanks! – Benjamin Tunney Nov 01 '16 at 19:22
1

I wrote a code used to count vowels. You may use this to count any character of your choosing. I hope this helps! (coded in Python 3.6.0)

while(True):
phrase = input('Enter phrase you wish to count vowels: ')
if phrase == 'end': #This will to be used to end the loop 
    quit() #You may use break command if you don't wish to quit
lower = str.lower(phrase) #Will make string lower case
convert = list(lower) #Convert sting into a list
a = convert.count('a') #This will count letter for the letter a
e = convert.count('e')
i = convert.count('i')
o = convert.count('o')
u = convert.count('u')

vowel = a + e + i + o + u #Used to find total sum of vowels

print ('Total vowels = ', vowel)
print ('a = ', a)
print ('e = ', e)
print ('i = ', i)
print ('o = ', o)
print ('u = ', u)
1

Suppose,

S = "Combination"

import re
print re.findall('a|e|i|o|u', S)

Prints: ['o', 'i', 'a', 'i', 'o']

For your case in a sentence (Case1):

txt = "blah blah blah...."

import re
txt = re.sub('[\r\t\n\d\,\.\!\?\\\/\(\)\[\]\{\}]+', " ", txt)
txt = re.sub('\s{2,}', " ", txt)
txt = txt.strip()
words = txt.split(' ')

for w in words:
    print w, len(re.findall('a|e|i|o|u', w))

Case2

import re,  from nltk.tokenize import word_tokenize

for w in work_tokenize(txt):
        print w, len(re.findall('a|e|i|o|u', w))
Pranzell
  • 2,275
  • 16
  • 21
1
from collections import Counter

count = Counter()
inputString = str(input("Please type a sentence: "))

for i in inputString:
    if i in "aeiouAEIOU":
          count.update(i)          
print(count)
fcdt
  • 2,371
  • 5
  • 14
  • 26
0
sentence = input("Enter a sentence: ").upper()
#create two lists
vowels = ['A','E',"I", "O", "U"]
num = [0,0,0,0,0]

#loop through every char
for i in range(len(sentence)):
#for every char, loop through vowels
  for v in range(len(vowels)):
    #if char matches vowels, increase num
      if sentence[i] == vowels[v]:
        num[v] += 1

for i in range(len(vowels)):
  print(vowels[i],":", num[i])
azaz
  • 35
  • 8
0
count = 0
s = "azcbobobEgghakl"
s = s.lower()
for i in range(0, len(s)):
    if s[i] == 'a'or s[i] == 'e'or s[i] == 'i'or s[i] == 'o'or s[i] == 'u':
        count += 1
print("Number of vowels: "+str(count))
Rishith Poloju
  • 171
  • 1
  • 3
0
string1='I love my India'

vowel='aeiou'

for i in vowel:
  print i + "->" + str(string1.count(i))
sushanth
  • 8,275
  • 3
  • 17
  • 28
  • 1
    Please read this [how-to-answer](http://stackoverflow.com/help/how-to-answer) for providing quality answer. It would be not a good answer if just include the code and without formatting. – thewaywewere May 28 '17 at 16:57
0

This works for me and also counts the consonants as well (think of it as a bonus) however, if you really don't want the consonant count all you have to do is delete the last for loop and the last variable at the top.

Her is the python code:

data = input('Please give me a string: ')
data = data.lower()
vowels = ['a','e','i','o','u']
consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowelCount = 0
consonantCount = 0


for string in data:
    for i in vowels:
        if string == i:
            vowelCount += 1
    for i in consonants:
        if string == i:
            consonantCount += 1

print('Your string contains %s vowels and %s consonants.' %(vowelCount, consonantCount))
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
0
Simplest Answer:

inputString = str(input("Please type a sentence: "))

vowel_count = 0

inputString =inputString.lower()

vowel_count+=inputString.count("a")
vowel_count+=inputString.count("e")
vowel_count+=inputString.count("i")
vowel_count+=inputString.count("o")
vowel_count+=inputString.count("u")

print(vowel_count)
GK Mali
  • 23
  • 7
  • Do you need str() function after input() ? Also if you have decided to use .count() function use it with loop for the len() of users input's each element. – JEX Mar 29 '19 at 22:56
0
from collections import defaultdict


def count_vowels(word):
    vowels = 'aeiouAEIOU'
    count = defaultdict(int)   # init counter
    for char in word:
        if char in vowels:
            count[char] += 1
    return count

A pythonic way to count vowels in a word, not like in java or c++, actually no need to preprocess the word string, no need for str.strip() or str.lower(). But if you'd like to count vowels case-insensitively, then before go into the for-loop, use str.lower().

Yossarian42
  • 1,950
  • 17
  • 14
0
vowels = ["a","e","i","o","u"]

def checkForVowels(some_string):
  #will save all counted vowel variables as key/value
  amountOfVowels = {}
  for i in vowels:
    # check for lower vowel variables
    if i in some_string:
      amountOfVowels[i] = some_string.count(i)
    #check for upper vowel variables
    elif i.upper() in some_string:
      amountOfVowels[i.upper()] = some_string.count(i.upper())
  return amountOfVowels

print(checkForVowels("sOmE string"))

You can test this code here : https://repl.it/repls/BlueSlateblueDecagons

So have fun hope helped a lil bit.

JEX
  • 124
  • 1
  • 6
0

...

vowels = "aioue"
text = input("Please enter your text: ")
count = 0

for i in text:
    if i in vowels:
        count += 1

print("There are", count, "vowels in your text")

...

  • 1
    This only counts the total number of vowels in the sentence, whereas the OP wants to get counts for specific characters. You can use it by specifying `vowels` for a single vowel only, but there is still a missing piece to get multiple counts for multiple vowels. – Richard Nemeth Jun 20 '19 at 17:56
0
def vowels():
    numOfVowels=0
    user=input("enter the sentence: ")
    for vowel in user:
        if vowel in "aeiouAEIOU":
            numOfVowels=numOfVowels+1
    return numOfVowels
print("The number of vowels are: "+str(vowels()))
csabinho
  • 1,579
  • 1
  • 18
  • 28
0

You could use regex and dict comprehension:

import re
s = "aeiouuaaieeeeeeee"

The regex function findall() returns a list containing all matches

Here x is the key and the lenght of the list returned by the regex is the count of each vowel in this string, note that regex will find any character you introduce into the "aeiou" string.

foo = {x: len(re.findall(f"{x}", s)) for x in "aeiou"}
print(foo)

returns:

{'a': 3, 'e': 9, 'i': 2, 'o': 1, 'u': 2}
fs1m
  • 1
0

This is a simple one don't feel it complex search for ternary for loop in python you will get it.

print(sum([1 for ele in input() if ele in "aeiouAEIOU"]))

THUNDER 07
  • 521
  • 5
  • 21
0
def vowel_count(string):
    
    string = string.lower()
    count = 0
    vowel_found = False 
    
    for char in string:
        if char in 'aeiou': #checking if char is a vowel
            count += 1
            vowel_found = True
            
    if vowel_found == False:
        print(f"There are no vowels in the string: {string}")
            
    return count

string = "helloworld"

result = vowel_count(string) #calling function

print("No of vowels are: ", result)
will-hedges
  • 1,254
  • 1
  • 9
  • 18
-1
def count_vowel():
    cnt = 0
    s = 'abcdiasdeokiomnguu'
    s_len = len(s)
    s_len = s_len - 1
    while s_len >= 0:
        if s[s_len] in ('aeiou'):
            cnt += 1
        s_len -= 1
    print 'numofVowels: ' + str(cnt)
    return cnt

def main():
    print(count_vowel())

main()
avina k
  • 19
  • 1
  • You've now posted three answers with blocks of code and no explanation or detail as to why your solution is the right answer. Please don't just post code blocks. – dimo414 Jun 23 '15 at 05:05
-1
count = 0
name=raw_input("Enter your name:")
for letter in name:
    if(letter in ['A','E','I','O','U','a','e','i','o','u']):
       count=count + 1
print "You have", count, "vowels in your name."
Abel.S
  • 19
  • 7
Simanto Bagchi
  • 81
  • 1
  • 2
  • 6
  • Welcome to So. However, there are several issues with your answer: 1) It doesn't actually explain anything to the OP 2) It's duplicative with another answer (that also doesn't break up the count for each of the vowels as the OP was trying to determine) – Foon Sep 03 '15 at 13:21
-1
  1 #!/usr/bin/python
  2 
  3 a = raw_input('Enter the statement: ')
  4 
  5 ########### To count number of words in the statement ##########
  6 
  7 words = len(a.split(' '))
  8 print 'Number of words in the statement are: %r' %words 
  9 
 10 ########### To count vowels in the statement ##########
 11 
 12 print '\n' "Below is the vowel's count in the statement" '\n'
 13 vowels = 'aeiou'
 14 
 15 for key in vowels:
 16     print  key, '=', a.lower().count(key)
 17 
huzeyfe
  • 3,554
  • 6
  • 39
  • 49
-1
def check_vowel(char):
    chars = char.lower()
    list = []
    list2 = []
    for i in range(0, len(chars)):
        if(chars[i]!=' '):
            if(chars[i]=='a' or chars[i]=='e' or chars[i]=='i' or chars[i]=='o' or chars[i]=='u'):
                list.append(chars[i])
            else:
                list2.append(chars[i])
    return list, list2
    

char = input("Enter your string:")
list,list2 = check_vowel(char)
if len(list)==1:
    print("Vowel is:", len(list), list)
if len(list)>1:
    print("Vowels are:", len(list), list)
if len(list2)==1:
    print("Constant is:", len(list2), list2)
if len(list2)>1:
    print("Constants are:", len(list2), list2)