Python program to count repeated characters in a string and display the count of repeated characters

Published by user on

In this post, we will see how to count repeated characters in a string.
Algorithm
Step 1: Declare a String and store it in a variable.
Step 2: Use 2 loops to find the duplicate characters. Outer loop will be used to select a character and initialize variable count to 1.
Step 3: Inner loop will be used to compare the selected character with remaining characters of the string.
Step 4: If a match found, it increases the count by 1.
Step 5: After completion of inner loop, if count of character is greater than 1, then it has duplicates in the string.
Step 6: Print all the repeated characters along with character count
Step 7: End
Example

Input: "welcome to the world of python programming"
Output:
Duplicate characters in a given string: 
w  -  2
e  -  3
l  -  2
o  -  6
m  -  3
t  -  3
h  -  2
r  -  3
p  -  2
n  -  2
g  -  2

Program

string = "welcome to the world of python programming";
   
print("Duplicate characters in a given string: ");  
for i in range(0, len(string)):  
    count = 1;  
    for j in range(i+1, len(string)):  
        if(string[i] == string[j] and string[i] != ' '):  
            count = count + 1;  
            string = string[:j] + '0' + string[j+1:];  
   
    if(count > 1 and string[i] != '0'):  
        print(string[i]," - ",count);

Output

Duplicate characters in a given string: 
w  -  2
e  -  3
l  -  2
o  -  6
m  -  3
t  -  3
h  -  2
r  -  3
p  -  2
n  -  2
g  -  2
Categories: python