0

I need to have a user enter a string in which any character is allowed. Once entered I need to count each letter character occurrence in the string. So far I have:

s = input("Enter a string: ") s = s.upper() all_freq = {} for i in s: if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 print(all_freq) 

This is wrong because it includes numbers, spaces and special characters in the count.

1
  • Perhaps an acceptable solution would be to compare the binary representation of the character with the binary representation of an ASCII character? Commented Mar 27, 2019 at 19:46

4 Answers 4

3

Using a list comprehension to filter and Counter (from collections) to count would make it more compact:

from collections import Counter s = "Hello World!" result = Counter(c for c in s.upper() if c.isalpha()) print(result) # Counter({'L': 3, 'O': 2, 'H': 1, 'E': 1, 'W': 1, 'R': 1, 'D': 1}) 
Sign up to request clarification or add additional context in comments.

Comments

1

If you only want to count characters, you can use the isalpha function to check if a character is alphabetical.

s = input("Enter a string: ") s = s.upper() all_freq = {} for i in s: if i.isalpha(): if i in all_freq: all_freq[i] += 1 else: all_freq[i] = 1 print(all_freq) 
Enter a string: Hello World! {'H': 1, 'E': 1, 'L': 3, 'O': 2, 'W': 1, 'R': 1, 'D': 1} 

Hope this helps!

Comments

0

You can also use regex expression to check for characters

import re s = input("Enter a string: ") s = s.upper() all_freq = {} for i in s: if bool(re.match('[A-Z]',i)): if i in all_freq : all_freq[i] += 1 else: all_freq[i] = 1 print(all_freq) 

Here's the output:

Enter a string: hello hello 1 $ {'H': 2, 'E': 2, 'L': 4, 'O': 2} 

Comments

0

Maybe one simple solution is to use string module like bellow:

import string s = input("Enter a string: ") ignore = string.whitespace + string.digits + string.punctuation s = s.upper() all_freq = {} for c in s: if c not in ignore: all_freq[c] = all_freq.get(c, 0) + 1 print(all_freq) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.