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?
-
3You don't need to do this, since a string is already a sequence of characters. Please provide some example of what you think you're doing.S.Lott– S.Lott2010-11-18 15:45:30 +00:00Commented Nov 18, 2010 at 15:45
-
3One difference between between a string and a list of characters is that a list is mutable. Is that why you want the sequence of character converted to that format? In many if not most other respects they are very similar and the same operations can be performed on either (so it might make sense to just leave them alone).martineau– martineau2010-11-18 16:00:17 +00:00Commented Nov 18, 2010 at 16:00
-
@martineau: But mutating a "string as list" isn't really very beneficial, since creating new strings is generally so efficient. It would be helpful to see some actual context around this question rather than guessing. I think it indicates a design problem, but without facts, it's hard to tell what the purpose is.S.Lott– S.Lott2010-11-18 18:31:39 +00:00Commented Nov 18, 2010 at 18:31
-
@S.Lott: What you say is uite true, I was just wondering out loud in the hopes that the OP would respond by agreeing or not and directly or indirectly provide some of the needed additional information -- doing what is requested is trivial, the motivation is the more interesting aspect.martineau– martineau2010-11-18 19:05:27 +00:00Commented Nov 18, 2010 at 19:05
3 Answers
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']
5 Comments
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
Comments
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.