How to find the frequency of every character in a string with Python

2 Answers

0 votes
def char_frequency(string):
    # Create an empty dictionary to store the frequency of each character
    frequency = {}
     
    for char in string:
        # If the character is already in the dictionary, increment its count
        if char in frequency:
            frequency[char] += 1
        # If the character is not in the dictionary, add it with a count of 1
        else:
            frequency[char] = 1
     
    return frequency
 
 
string = "Python is a general-purpose programming language"

result = char_frequency(string);

for key, value in result.items():
     print(key, value)
 
 
 
'''
run:
 
P 1
y 1
t 1
h 1
o 3
n 4
  5
i 2
s 2
a 5
g 5
e 4
r 4
l 2
- 1
p 3
u 2
m 2
 
'''

 



answered Nov 24, 2024 by avibootz
edited Nov 24, 2024 by avibootz
0 votes
from collections import Counter

string = "Python is a general-purpose programming language"

char_frequency = Counter(string)

for key, value in char_frequency.items():
     print(key, value)



'''
run:

P 1
y 1
t 1
h 1
o 3
n 4
  5
i 2
s 2
a 5
g 5
e 4
r 4
l 2
- 1
p 3
u 2
m 2

'''

 



answered Nov 24, 2024 by avibootz
edited Nov 24, 2024 by avibootz
...