0

This code prints a table of the letters of the alphabet in alphabetical order which occur in the string together with the number of times each letter occurs. There are two unwanted numbers in this code which are 8 and .1 but I do not know how to remove them from the output.

 s = 'ThiS is String with Upper and lower case Letters.' # Or see Python's Counter class: counts = Counter(s.lower()) counts = {} for c in s.lower(): counts[c] = counts.get(c, 0) + 1 for c, n in sorted(counts.items()): print(c, n) 
4
  • 8 is the number of space " " in the string. Commented Nov 27, 2020 at 21:40
  • Then I guess "1" is for the dot(.). Commented Nov 27, 2020 at 21:41
  • I do not want that in the output lol. How can I change that so that those two numbers do not show? Commented Nov 27, 2020 at 21:43
  • See stackoverflow.com/questions/15558392/… Commented Nov 27, 2020 at 21:46

5 Answers 5

2

Purely for fun ... you could do it all in two lines if you really wanted. :-)

String:

 s = 'ThiS is String with Upper and lower case Letters.' 

Ridiculousness:

chars = [i for i in s.lower() if i.isalpha()] print(*sorted({c: chars.count(c) for c in chars}.items(), key=lambda x: x[1], reverse=True), sep='\n') 

Output:

('t', 5) ('s', 5) ('e', 5) ('i', 4) ('r', 4) ('h', 2) ('n', 2) ('w', 2) ('p', 2) ('a', 2) ('l', 2) ('g', 1) ('u', 1) ('d', 1) ('o', 1) ('c', 1) 
Sign up to request clarification or add additional context in comments.

Comments

1

So,You can remove spaces and dots from the input string.

s = 'ThiS is String with Upper and lower case Letters.' s=s.replace(" ","").replace(".","")# remove spaces and dots from the input string counts = {} for c in s.lower(): counts[c] = counts.get(c, 0) + 1 for c, n in sorted(counts.items()): print(c, n) 

[Output]:

a 2 c 1 d 1 e 5 g 1 h 2 i 4 l 2 n 2 o 1 p 2 r 4 s 5 t 5 u 1 w 2 

1 Comment

Instead of chaining replaces, you can do this in a more pythonic way: s = "".join(c for c in s if c.isalpha())
1

It looks like it's counting spaces and periods in the string as well. Replacing them with "" is an easy way to fix this.

Comments

1
import string from collections import Counter s = "".join(filter(lambda c: c in string.ascii_letters, s)) for c, count in Counter(s).items(): print(c, count) 

Comments

0

You can simply count them using str.count() with a simple check of isalpha():

s = 'ThiS is String with Upper and lower case Letters. 81' {char: s.count(char) for char in s.lower() if char.isalpha()} 

results in:

{'t': 4, 'h': 2, 'i': 4, 's': 3, 'r': 4, 'n': 2, 'g': 1, 'w': 2, 'u': 0, 'p': 2, 'e': 5, 'a': 2, 'd': 1, 'l': 1, 'o': 1, 'c': 1} 

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.