nature7
nature7

Reputation: 5

Function to count upper/lower case letters

Could you please help me with writing a function to count alphabetic characters. My current output for this code is like this:

It contains 5 alphabetic characters of which 4 ( 80.0 %) are 'h'

My output for this code should be like this: It contains 5 alphabetic characters of which 5 ( 100.0 %) are 'h'. I would like to treat both upper/lowercase letters equally

def count(p):
    lows = "abcdefghijklmnopqrstuvwxyz"
    ups =  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

    numberOfh = 0
    totalChars = 0
    for achar in p:
        if achar in lows or achar in ups:
            totalChars = totalChars + 1
            if achar == 'h':
                numberOfh = numberOfh + 1

    percent_with_h = (numberOfh / totalChars) * 100
    print("It contains", totalChars, "alphabetic characters of which", numberOfh, "(", percent_with_h, "%)", "are 'h'.")


p = "Hhhhh"
count(p)

Upvotes: 0

Views: 155

Answers (3)

tale852150
tale852150

Reputation: 1628

Just change if statement to

if achar == 'h' or achar == 'H':

If you want to count all 'h' and 'H'.

Upvotes: 0

Brendan Duck
Brendan Duck

Reputation: 11

If you want to count the occurrence of any letter in your string, rather than just h you could use something like this, which returns a dictionary containing each letter as the key, and the percentage as the value:

    def count_alphas(s):
        s = s.lower()
        alpha_set = set(s)
        alpha_counts = {}

        for x in alpha_set: 
            alpha_counts[x] = s.count(x) / float(len(s)) * 100

        return alpha_counts

    # an example use:
    print(count_alphas('thisissomeexampletext'))

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 113998

print p.lower().count("h")

I think should do what you want

Upvotes: 1

Related Questions