[Tutor] String to List and back?

Chinook chinook.nr at tds.net
Sun Jul 3 05:45:28 CEST 2005


I'm missing something simple again.  The simplified issue is:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10)

 >>> mystr = 'abc'

  # I can create a list of the string characters
  #  with list comprehension
 >>> [c for c in mystr]
['a', 'b', 'c']

  # Or just a simple builtin conversion function
 >>> list(mystr)
['a', 'b', 'c']

  # But a conversion back to a string simply makes the
  #  the list a string (I know there would have to be
  #  special handling, but I noted it for illustration)
 >>> str(['a', 'b', 'c'])
"['a', 'b', 'c']"

  # I know I could get the original string back by
  #  rebuilding it with "for" loop
 >>> bts = ''
 >>> for c in strlist:
...   bts += c
...
 >>> bts
'abc'

  # or even a function or class method which implemented
  #  the "for" loop
  # I could also build a new string directly from the
  #  original with a "for" loop

Is there a one-liner like a builtin conversion function or list 
comprehension technique for the reverse (i.e. a list of strings back to 
a single string)?

Thank you,

Lee C



More information about the Tutor mailing list