transforming a list into a string

kosh kosh at aesaeion.com
Mon Aug 2 10:51:44 CEST 2004


On Saturday 31 July 2004 6:44 am, Peter Otten wrote:
> jblazi wrote:
> > Let us assume I have a list like
> >
> > ['1','2','7','8','12','13]
> >
> > and would like to transoform it into the string
> >
> > '{1,2},{7,8},{12,13}'
> >
> > Which is the simplest way of achiebing this? (The list is in fact much
> > longer and I may have to cut the resulting strings into chunks of 100 or
> > so.)
> >
> >>> from itertools import izip
> >>> items = ['1','2','7','8','12','13']
> >>> it = iter(items)
> >>> ",".join(["{%s,%s}" % i for i in izip(it, it)])
>
> '{1,2},{7,8},{12,13}'
>
>
> Peter

This way also works I am not sure how it compares on large sets for memory 
usage, cpu time etc.

items = ['1','2','7','8','12','13']
if len(items)%2 == 0:
    #the len check is to make sure that the length of the set is evenly 
    #divisible by 2
    output = "{%s,%s}" * (len(items)/2)% tuple(items)



More information about the Python-list mailing list