purple purple - 5 months ago 18
Python Question

Print custom string with character and character count without using python built-in methods

I would like to tweak my string to print the character and the character count without using python built-in methods.

>>> string = 'aaaabbbddd'


I am looking for this output:

a4b3d3

Answer

Here is a way to do it with no built in methods!

def count_modify(string):
    d = {}
    for i in string:
        if i in d:
            d[i] += 1
        else:
            d[i] = 1
    return ''.join(str(x)+str(d[x]) for x in d)

Alternatively you could decide to not use the join() method and instead do the following

def count_modify(string):
        d = {}
        for i in string:
            if i in d:
                d[i] += 1
            else:
                d[i] = 1
        n_str = ''
        for i in d:
            n_str += str(i)+str(d[i])
        return n_str

Now the only obvious methods used are the str() methods!

Comments