10

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 how to split a word into letters:

word = "word"
word.split("")

Throws me an error. Ideally I want it to return ['w','o','r','d'] thats why the split argument is "".

user1103294
  • 423
  • 3
  • 6
  • 16

5 Answers5

27
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
iblazevic
  • 2,713
  • 2
  • 23
  • 38
5

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']
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
4

list(word)

you can pass it to list

>>> list('word')
['w', 'o', 'r', 'd']
dm03514
  • 54,664
  • 18
  • 108
  • 145
3

In python send it to

    list(word)
apollosoftware.org
  • 12,161
  • 4
  • 48
  • 69
2

You can iterate over each letter in a string like this:

>>> word = "word"
>>> for letter in word:
...     print letter;
...
w
o
r
d
>>>
CraigTeegarden
  • 8,173
  • 8
  • 38
  • 43