Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting output as character and it's occurrence in the string

The input I gave is like this

Input- abccdddeffg

and the output I want is character and it’s occurrence number

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output- a1b1c2d3e1f2g1

my code

uni = []
string = 'abcccdd'
for i in range(0, len(string)):
    for j in range(i+1, len(string)):
        if (string[i] == string[j]):
            uni.append(string[i])
            
for oc in uni:
    cou= uni.count(oc)
    print(oc,cou)

Thanks in advance

>Solution :

You can use the Counter from collections to get the count of every character in the list. Then use a forloop to generate your result and use set to make sure no character is repeated in the result.

from collections import Counter    
string = "abccdddeffg"
counts = Counter(string)
sets = set()
result = []

for s in string:
    if s not in sets:
        result.append(f"{s}{counts[s]}")
    sets.add(s)

result = ''.join(result)
print(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading