Home > OS >  Take a string and return a new string with each characters and their occurence
Take a string and return a new string with each characters and their occurence

Time:10-20

How would you create a Python function that takes a string and returns a new string that contains the characters of the given string once each (without repetitions), in the same order, and with their number of repetitions. For example, if the given string is "aaaabbbbccddde", the result would be "a4b4c2d3e1".

CodePudding user response:

You can iterate through the set and append the count along with it. So, there might be a chance of changing the order of values. So you can do this.

from collections import OrderedDict
result = ''.join(i str(s.count(i)) for i in list(OrderedDict.fromkeys(s)))

Execution,

In [1]: s = 'aaaabbbbccddde'

In [2]: ''.join(i str(s.count(i)) for i in list(OrderedDict.fromkeys(s)))
Out[2]: 'a4b4c2d3e1'

CodePudding user response:

Try itertools.groupby:

from itertools import groupby

s = "aaaabbbbccddde"

out = "".join(f"{v}{sum(1 for _ in g)}" for v, g in groupby(s))
print(out)

Prints:

a4b4c2d3e1

CodePudding user response:

One class in the Python standard library is the Counter class (from collections import Counter). This counts the occurrences of any character into a dict-like. For your use case, it can be used like this:

from collections import Counter

string = "aaaabbbbccddde"
counter = Counter(string)

new_string = “”

# loops over each letter
for letter in counter.keys():
    # adds the letter and the number of occurences to new_string
    new_string  = letter   counter[letter]
  • Related