Entry
Convertings strings to/from lists
Convertings strings to/from lists
Oct 18th, 2002 12:32
Allan Caetano, Nathan Wallace, unknown unknown, Hans Nowak, Snippet 8, Tim O'Malley
"""
Packages: basic_datatypes.lists;basic_datatypes.strings
"""
"""
> conversion of a string to a list is easy (and in the FAQ!):
>
"""
print map(None, "string")
"""
The FAQ should be updated to include Python 1.5's easier way:
"""
print list("a string")
# ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
"""
> conversion of a list to a string depends on what sort of string you
want
> to create:
"""
print str([1,2]) # yields '[1, 2]'
import string
print string.join(map(str, [1,2])) # yields "1 2"
print string.join(map(str, ([1,2])), "") # yields "12"
"""
Assuming the original poster wanted to simply reverse the list()
process, the simplest way is a string.join() call:
"""
A = list("a string")
print A
# ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
print string.join(A, "")
# 'a string'
"""
The solution using string.join() is the simplest, but
using reduce in unexpected ways can also be fun. Plus,
it works even if some of the elements in the list are
not characters, though I doubt someone would find that
useful.
"""
A = list('a string')
# ['a', ' ', 's', 't', 'r', 'i', 'n', 'g']
reduce(lambda x,y: x + str(y), A)
# 'a string'
A.insert(4, 42.0)
# ['a', ' ', 's', 't', 42.0, 'r', 'i', 'n', 'g']
reduce(lambda x,y: str(x) + str(y), A)
# 'a st42.0ring' Whatever!!!