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)
S3DEV
  • 8,768
  • 3
  • 31
  • 42
Johhhbb
  • 1
  • 1
  • 4

5 Answers5

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)
S3DEV
  • 8,768
  • 3
  • 31
  • 42
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
AziMez
  • 2,014
  • 1
  • 6
  • 16
  • 2
    Instead of chaining `replace`s, you can do this in a more pythonic way: `s = "".join(c for c in s if c.isalpha())` – kn0wmad1c Nov 27 '20 at 21:51
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.

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)
Daniel Meltzer
  • 349
  • 1
  • 3
  • 10
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}
Hamza
  • 5,373
  • 3
  • 28
  • 43