TAGS :Viewed: 11 - Published at: a few seconds ago

[ Splitting a string into a list in python ]

I have a long string of characters which I want to split into a list of the individual characters. I want to include the whitespaces as members of the list too. How do I do this?

Answer 1


you can do:

list('foo')

spaces will be treated as list members (though not grouped together, but you didn't specify you needed that)

>>> list('foo')
['f', 'o', 'o']
>>> list('f oo')
['f', ' ', 'o', 'o']

Answer 2


Here some comparision on string and list of strings, and another way to make list out of string explicitely for fun, in real life use list():

b='foo of zoo'
a= [c for c in b]
a[0] = 'b'
print 'Item assignment to list and join:',''.join(a)

try:
    b[0] = 'b'
except TypeError:
    print 'Not mutable string, need to slice:'
    b= 'b'+b[1:]

print b

Answer 3


This isn't an answer to the original question but to your 'how do I use the dict option' (to simulate a 2D array) in comments above:

WIDTH = 5
HEIGHT = 5

# a dict to be used as a 2D array:
grid = {}

# initialize the grid to spaces
for x in range(WIDTH):
    for y in range(HEIGHT):
        grid[ (x,y) ] = ' '

# drop a few Xs
grid[ (1,1) ] = 'X'
grid[ (3,2) ] = 'X' 
grid[ (0,4) ] = 'X'

# iterate over the grid in raster order
for x in range(WIDTH):
    for y in range(HEIGHT):
        if grid[ (x,y) ] == 'X':
            print "X found at %d,%d"%(x,y)

# iterate over the grid in arbitrary order, but once per cell
count = 0
for coord,contents in grid.iteritems():
    if contents == 'X':
        count += 1

print "found %d Xs"%(count)

Tuples, being immutable, make perfectly good dictionary keys. Cells in the grid don't exist until you assign to them, so it's very efficient for sparse arrays if that's your thing.