Convert A Word To A List Of Chars
I can split a sentence into individual words like so: string = 'This is a string, with words!' string.split(' ') ['This', 'is', 'a', 'string,', 'with', 'words!'] But I don't know
Solution 1:
>>> s = "foobar">>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
Solution 2:
In Python string is iterable. This means it supports special protocol.
>>>s = '123'>>>i = iter(s)>>>i
<iterator object at 0x00E82C50>
>>>i.next()
'1'
>>>i.next()
'2'
>>>i.next()
'3'
>>>i.next()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
i.next()
StopIteration
list constructor may build list of any iterable. It relies on this special method next and gets letter by letter from string until it encounters StopIteration.
So, the easiest way to make a list of letters from string is to feed it to list constructor:
>>> list(s)
['1', '2', '3']Solution 3:
list(word)
you can pass it to list
>>> list('word')
['w', 'o', 'r', 'd']Solution 4:
In python send it to
list(word)
Solution 5:
You can iterate over each letter in a string like this:
>>>word = "word">>>for letter in word:...print letter;...
w
o
r
d
>>>
Post a Comment for "Convert A Word To A List Of Chars"