0

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)
nature7
  • 5
  • 4
  • 1
    Possible duplicate of [How to convert string to lowercase in Python?](http://stackoverflow.com/questions/6797984/how-to-convert-string-to-lowercase-in-python) – Ken Y-N Jul 11 '16 at 23:59

3 Answers3

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

I think should do what you want

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

Just change if statement to

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

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

tale852150
  • 1,618
  • 3
  • 17
  • 23
0

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'))