How to split a string into a list of characters in Python?
I've tried to look around the web for answers to splitting a string into a list of characters but I can't seem to find a simple method.
str.split(//)
does not seem to work like Ruby does. Is there a simple way of doing this without looping?
Solution 1:
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
You need list
Solution 2:
You take the string and pass it to list()
s = "mystring"
l = list(s)
print l
Solution 3:
You can also do it in this very simple way without list():
>>> [c for c in "foobar"]
['f', 'o', 'o', 'b', 'a', 'r']
Solution 4:
If you want to process your String one character at a time. you have various options.
uhello = u'Hello\u0020World'
Using List comprehension:
print([x for x in uhello])
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using map:
print(list(map(lambda c2: c2, uhello)))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Calling Built in list function:
print(list(uhello))
Output:
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using for loop:
for c in uhello:
print(c)
Output:
H
e
l
l
o
W
o
r
l
d