"Stringizing" a list

Ole Martin Bjoerndalen olemb at stud.cs.uit.no
Wed Aug 9 09:48:33 EDT 2000


cg at gaia.cdg.acriter.nl (Cees de Groot) writes:

> I'm sure I've seen a place with a snippet for this, but I couldn't find it:
> 
> what's the cleanest way to convert a random nested list structure like:
> 
> ['foo', ['bar', 'baz'], 'quux']
> 
> into:
> 
> 'foo bar baz quux' ?
> 
> I've, ahem, solved this with a bit of recursion and relying on '+' to throw
> in certain circumstances, but it's a hairy and ugly piece of code. 

How about:

import string 
 
def stringize(s): 
    if type(s) == type(''): 
        return s 
    else: 
        return string.join(map(stringize, s)) 

>>> stringize(['foo', ['bar', 'baz'], 'quux'])
'foo bar baz quux'


-- 
   Ole Martin Bjoerndalen
 http://www.cs.uit.no/~olemb/ 
    olemb at stud.cs.uit.no



More information about the Python-list mailing list