"Stringizing" a list

Cezar Ionescu ionescu at pik-potsdam.de
Wed Aug 9 10:55:26 EDT 2000


[Cees de Groot]
> 
> 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' ?

Yes, I also think I saw this before. Anyway, how about:

from types import ListType, TupleType

def stringit(aSeq, aString=''):
    if len(aSeq) == 0:
        return aString[:-1] # to get rid of the extra blank
    if type(aSeq[0]) in (ListType, TupleType):
        return stringit(aSeq[1:], aString + stringit(aSeq[0]) + ' ')
    else:
        return stringit(aSeq[1:], aString + ' ' + aSeq[0] + ' ')

if __name__ == "__main__":
    aStringSeq = ['aaa', 'bbb', ['ccc', ('ddd', 'eee'), 'fff'], 'ggg']
    result = stringit(aStringSeq)
    print result

The result is:

'aaa bbb ccc ddd eee fff ggg'

Best,
Cezar.



More information about the Python-list mailing list