I\'ve tried to look around the web for answers to splitting a string into an array of characters but I can\'t seem to find a simple method
str.split(//)
from itertools import chain
string = 'your string'
chain(string)
similar to list(string)
but returns a generator that is lazily evaluated at point of use, so memory efficient.
You take the string and pass it to list()
s = "mystring"
l = list(s)
print l
You can also do it in this very simple way without list():
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
You can use extend
method in list operations as well.
>>> list1 = []
>>> list1.extend('somestring')
>>> list1
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
I explored another two ways to accomplish this task. It may be helpful for someone.
The first one is easy:
In [25]: a = []
In [26]: s = 'foobar'
In [27]: a += s
In [28]: a
Out[28]: ['f', 'o', 'o', 'b', 'a', 'r']
And the second one use map and lambda
function. It may be appropriate for more complex tasks:
In [36]: s = 'foobar12'
In [37]: a = map(lambda c: c, s)
In [38]: a
Out[38]: ['f', 'o', 'o', 'b', 'a', 'r', '1', '2']
For example
# isdigit, isspace or another facilities such as regexp may be used
In [40]: a = map(lambda c: c if c.isalpha() else '', s)
In [41]: a
Out[41]: ['f', 'o', 'o', 'b', 'a', 'r', '', '']
See python docs for more methods
I you just need an array of chars:
arr = list(str)
If you want to split the str by a particular str:
# str = "temp//temps" will will be ['temp', 'temps']
arr = str.split("//")