Search code examples
pythonfunctionprintingsplitsentence

How can I use the split() function to figure out how many vowels there are in total?


How can I use the split() function to figure out how many vowels there are in total? How can I print the number of a, e, i, o, and u in each of these sentences? The sentence is

'I study Python programming at KAIST Center For Gifted Education'

umm.... counter is not working guys..(i mean I want you to give me details one by one, not the built-in function of the basic Python, So that it can work on other coding programs.


Solution

  • I would suggest using collections.Counter(), e.g. like this:

    from collections import Counter
    
    sentence = 'I study Python programming at KAIST Center For Gifted Education'
    
    counts = Counter(sentence)
    
    print(counts['a'])
    # 3
    print(counts['A'])
    # 1
    print(counts['e'])
    # 3
    print(counts['E'])
    # 1
    print(counts['i'])
    # 3
    print(counts['I'])
    # 2
    print(counts['o'])
    # 4
    print(counts['O'])
    # 0
    print(counts['u'])
    # 2
    print(counts['U'])
    # 0
    

    If you'd like to count the vowels case-independently you can call .lower() on the sentence before passing it to Counter(), e.g.:

    from collections import Counter
    
    sentence = 'I study Python programming at KAIST Center For Gifted Education'
    
    counts = Counter(sentence.lower())
    
    print(counts['a'])
    # 4
    print(counts['e'])
    # 4
    print(counts['i'])
    # 5
    print(counts['o'])
    # 4
    print(counts['u'])
    # 2
    

    EDIT:

    If for some reason you cannot use the collections library, strings have a count() method:

    sentence = 'I study Python programming at KAIST Center For Gifted Education'
    
    print(sentence.count('a'))
    # 3
    print(sentence.count('e'))
    # 3
    print(sentence.count('i'))
    # 3
    print(sentence.count('o'))
    # 4
    print(sentence.count('u'))
    # 2
    

    In case you'd like to count more than just vowels, it may be more efficient to "manually" count the sub-strings (i.e. vowels in your case), e.g.:

    sentence = 'I study Python programming at KAIST Center For Gifted Education'
    
    # Initialise counters:
    vowels = {
        'a': 0,
        'e': 0,
        'i': 0,
        'o': 0,
        'u': 0,
    }
    
    for char in sentence:
        if char in vowels:
            vowels[char] += 1
    
    print(vowels['a'])
    # 3
    print(vowels['e'])
    # 3
    print(vowels['i'])
    # 3
    print(vowels['o'])
    # 4
    print(vowels['u'])
    # 2