list to string

Glenn W Jackman glennj at pcard31e.ca.nortel.com
Tue Feb 27 10:16:40 EST 2001


Daniel Klein wrote:
>On Tue, 27 Feb 2001 07:22:03 GMT, Sheila King <sheila at spamcop.net> wrote:
>>:>>> lst =["d", "o", "g"]
>>:>>> dog = lst[0]+lst[1]+lst[2]
>>
>>Your method would be awfully tedious for very long strings. You want something
>>that will be easy to implement, regardless of the length of the string.
>>Fortunately, several others in this thread have already suggested using the
>>join command from the string methods.
>
>mylist = ['d','o','g']
>mystring = ''
>for element in mylist:
>      mystring = mystring + element

>It's simple and intuitive. I know that it has to build a _new_ string each time
>but for shorter strings...

Having just read "Learning Python", I offer:

>>> import operator
>>> s = '''Python 1.5.2 (#1, Feb  1 2000, 16:32:16)  [GCC egcs-2.91.66 19990314/Linux (egcs- on linux-i386
... Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam'''
>>> l = list(s)           
>>> s2 = reduce(operator.add, l)
>>> s == s2
1
>>> s is s2
0

-- 
Glenn 



More information about the Python-list mailing list