Question

Is there a function in python to split a word into a list of single letters? e.g:

s="Word to Split"

to get

wordlist=['W','o','r','d','','t','o' ....]
Was it helpful?

Solution

>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']

OTHER TIPS

The easiest way is probably just to use list(), but there is at least one other option as well:

s = "Word to Split"
wordlist = list(s)               # option 1, 
wordlist = [ch for ch in s]      # option 2, list comprehension.

They should both give you what you need:

['W','o','r','d',' ','t','o',' ','S','p','l','i','t']

As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:

[doSomethingWith(ch) for ch in s]

Abuse of the rules, same result: (x for x in 'Word to split')

Actually an iterator, not a list. But it's likely you won't really care.

The list function will do this

>>> list('foo')
['f', 'o', 'o']
text = "just trying out"

word_list = []

for i in range(0, len(text)):
    word_list.append(text[i])
    i+=1

print(word_list)

['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top