Home > Enterprise >  Converting string in python by counting letters next to eachother
Converting string in python by counting letters next to eachother

Time:11-12

I tried many ways but neither worked. I have to convert string like assdggg to a2sd3g in python. If letters are next to each other we leave only one letter and before it we write how mamy of them were next to eachother. Any idea how can it be done?

CodePudding user response:

I'd suggest itertools.groupby then format as you need

from itertools import groupby

# groupby("assdggg")
# {'a': ['a'], 's': ['s', 's'], 'd': ['d'], 'g': ['g', 'g', 'g']}

result = ""
for k, v in groupby("assdggg"):
    count = len(list(v))
    result  = (str(count) if count > 1 else "")   k

print(result)  # a2sd3g

CodePudding user response:

You can use collections.Counter, then if count_of_char > 1 set count else set '' like below:

>>> from collections import Counter
>>> st = 'assdggg'
>>> cnt_chr = Counter(st)
>>> cnt_chr
Counter({'a': 1, 's': 2, 'd': 1, 'g': 3})

>>> ''.join(f"{'' if cnt==1 else cnt}{c}" for c , cnt in cnt_chr.items())
'a2sd3g'

CodePudding user response:

Try using .groupby():

from itertools import groupby

txt = "assdggg"

print(''.join(str(l)   k if (l := len(list(g))) != 1 else k for k, g in groupby(txt)))

output :

a2sd3g

CodePudding user response:

You can try this :

string = 'assdggg'
compression = ''

for char in string :
    if char not in compression :
        if string.count(char) != 1 :
            compression  = str(string.count(char))
        compression  = char

print(compression)
#'a2sd3g'
  • Related