Python: Count Characters in String
You can use the Counter class in the collections library to count the occurrences of characters in a string. Here’s an example:
from collections import Counter
s = "hello world"
counts = Counter(s)
for char, count in counts.items():
print(f"{char}: {count}")
By running the code above, the output result will be:
h: 1
e: 1
l: 3
o: 2
: 1
w: 1
r: 1
d: 1