how do i change from string to list

Andrew Dalke adalke at mindspring.com
Mon Oct 25 04:30:08 EDT 2004


Michael Hoffman wrote:
>>>>> ''.join(["H", "e", "l", "l", "o"])

> That is the obvious way to do it.

As compared to the less obvious ways of


 >>> import array
 >>> array.array("c", list("this is a test")).tostring()
'this is a test'
 >>>

 >>> import cStringIO
 >>> f = cStringIO.StringIO()
 >>> for c in list("this is a test"):
...   f.write(c)
...
 >>> print f.getvalue()
this is a test
 >>>

 >>> import operator
 >>> reduce(operator.add, list("this is a test"))
'this is a test'
 >>>

 >>> def join(fields):
...   N = len(fields)
...   if N == 1: return fields[0]
...   if N == 2: return fields[0] + fields[1]
...   N = N//2
...   return join([join(fields[:N]), join(fields[N:])])
...
 >>> join(list("this is a test"))
'this is a test'
 >>>


   # only works for single character elements in the list
   # (or larger strings that don't have ", ")
 >>> s = "\"Let's go to the zoo!\", said \\Alice/\n"
 >>> print s
"Let's go to the zoo!", said \Alice/

 >>> list(s)
['"', 'L', 'e', 't', "'", 's', ' ', 'g', 'o', ' ', 't', 'o', ' ', 't', 
'h', 'e', ' ', 'z', 'o', 'o', '!', '"', ',', ' ', 's', 'a', 'i', 'd', ' 
', '\\', 'A', 'l', 'i', 'c', 'e', '/', '\n']
 >>> print eval(repr(list(s))[1:-1].replace(", ", " "))
"Let's go to the zoo!", said \Alice/

 >>>

   :)

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list