03131992 03131992 - 1 month ago 7
Python Question

How to remove brackets and commas from tuple

I'm trying to get the top 5 characters of a string printed.
For example, if I typed "aaaabbbbcccddfg"

Is there anyway I can change the output so it becomes a:4,b:4,c:3,d:2,f:1 ?

Codes are:

import sys
from collections import Counter

try:
string = sys.argv[1]

counts=Counter(string.lower()) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
lista = counts.most_common(5)

print lista

except ValueError:
print "Error"


The current result is: [("a", 4),("b", 4), ("c", 3), ("d", 2), ("f", 1)]

Answer Source

Works for python 2.7:

from __future__ import print_function
import sys
from collections import Counter

try:
    string = sys.argv[1]
    counts=Counter(string.lower()) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
    lista = counts.most_common(5)
    print (lista)
    for l in lista:
        print(':'.join(str(e) for e in l), end=",")

except ValueError:
    print ("Error")