transforming a list into a string

Roy Smith roy at panix.com
Sat Jul 31 09:06:47 EDT 2004


In article <pan.2004.07.31.12.27.23.547000 at hotmail.com>,
 jblazi <jblazi at hotmail.com> wrote:

> Let us assume I have a list like
> 
> ['1','2','7','8','12','13]

I'm assuming there's supposed to be another single-quote after the 13?

> and would like to transoform it into the string
> 
> '{1,2},{7,8},{12,13}'

This works, and is pretty straight-forward:

source = ['1','2','7','8','12','13']
temp = []

while source:
    x = source.pop(0)
    y = source.pop(0)
    temp.append ('{%s,%s}' % (x, y))

result = ','.join (temp)
print result

This prints what you want:

$ /tmp/list2string.py 
{1,2},{7,8},{12,13}

Accumulating the repeating bits of the result string in a list, and then 
putting them together with a join operation is a common idiom in python.  
You can build up strings by doing string addition:

temp = temp + '{%s,%s}' % (x, y)

This will have the same result, but suffers from quadratic run times as 
it keeps building and destroying immutable strings.

> 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.)

How long is "much longer", and how important is it that this runs fast?  
The code above runs in O(n).  You can probably play some tricks to tweak 
the speed a little, but in the big picture, you're not going to do any 
better than O(n).

The above code also assumes you have an even number of items in source, 
and will bomb if you don't.  You probably want to fix that :-)



More information about the Python-list mailing list