Ada
Ada

Reputation: 91

Count symbols Char's in String Python

I'd like to count repetead chars in string, I know about count() function, but it doesn't helps me in my current task. For example , the String Sample Input is : s = 'aaaabbсaa' Sample Output should be :a4b2с1a2 I will appreciate for any suggestions, thank you.

Upvotes: 1

Views: 107

Answers (2)

Juan Samuel
Juan Samuel

Reputation: 11

You can try this as well:

s = 'aaaabbсaa'
new_s=''
num=0
prev=s[0]
for i in range(len(s)):
    if(s[i]==prev):
       num += 1
    else:
       new_s+=s[i-1]
       new_s+=str(num)
       prev=s[i]
       num=1
    if(i==len(s)-1)
       new_s+=s[i]
       new_s+=str(num)

print(new_s)

Output:

'a4b2c1a2'

Upvotes: 1

MrNobody33
MrNobody33

Reputation: 6483

You can try with itertools.groupby:

s = 'aaaabbсaa'

from itertools import groupby

result=''.join(f'{label}{len(list(group))}' for label, group in groupby(s))
#same as: 
#result = [f'{label}{len(list(group))}' for label, group in groupby(s)]
#result=''.join(result)

Output:

result
'a4b2с1a2'

Upvotes: 2

Related Questions