Search code examples
pythonstringcountintegerconcatenation

How to convert a comma separated string of numbers to a number?


I want to convert a comma separated list of numbers into the number itself and number of times each number appeared appended at the end of appearance of that number, like this:

"2,5,6,9,2,5,8,2,7,1,1,1,4"

If this is the string, removing the commas will give :

2569258271114

But I want this:

256191252823711341

Let say the number 2 appeared 3 times, so i want to write 3 after the last appearance of number '2' which appears in the above number at ...823.... And so on.

I am stuck, I can do it the long way, but I need a short code. A pythonic way of solving the problem :) Any help will be appreciated. TIA


Solution

  • Here is how you can use Counter from the collections module, and str.find():

    from collections import Counter
    
    s = "2,5,6,9,2,5,8,2,7,1,1,1,4"
    s = s.replace(',','') # Removes all commas
    n = Counter(s) # Dictionary with different numbers as keys and their frequency as values
    
    for a in n: # For every different number in n
        i = s.rfind(a) # Finds the index of the last appearance of the number
        s = s[:i+1]+str(n[a])+s[i+1:] # Inserts the frequency of the number on the right of the last appearance of it
        
    print(s)
    

    Output:

    256191252812371111341