list manipulation

John Machin sjmachin at lexicon.net
Tue Apr 22 17:50:10 EDT 2008


Joe Riopel wrote:
> On Tue, Apr 22, 2008 at 4:55 PM, DataSmash <rdh at new.rr.com> wrote:
>> Hello,
>>
>>  I have a list that looks like this:
>>  roadList = ["Motorways","Local","Arterial"]
>>
>>  I want to apply some code so that the output looks like this:
>>  "Motorways;Local;Arterial"
>>  How can this be done with the LEAST amount of code?
> 
> Not sure if it's LEAST amount of code, or the best, but it works.

It's definitely not the least (see below) and it doesn't work -- it puts 
a ; after the last list item.

> 
>>>> li = ["Motorways","Local","Arterial"]
>>>> '\"%s\"' % (''.join(['%s;' % (x,) for x in li]),)
> '"Motorways;Local;Arterial;"'

That is littered with redundant punctuation. Removing it:

 >>> '"%s"' % ''.join('%s;' % x for x in li)
'"Motorways;Local;Arterial;"'

Note: that would need the [] put back for Python < 2.4. But in any case 
we can further reduce it like this:

 >>> '"%s;"' % ';'.join(li)
'"Motorways;Local;Arterial;"'
 >>>

Now we have minimal, legible code which works on Python back to 2.1 at 
least and  is only one thump of the Delete key away from what the OP 
asked for.

HTH,
John






More information about the Python-list mailing list