>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
Answer from Greg Hewgill on Stack Overflow>>> list("Word to Split")
['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
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]
Is it possible to make python split a word into letters?
How to split a word into letters in Python - Stack Overflow
split() function splitting every character?
How to split each string into words and collects all words in a new list.
Is there a code line that can do that? Print sunny as 's','u','n','n','y'?
Every other time I have used the split function, it splits at the spaces but this time it is different. Here is my code:
c = "add 17 92 403" c.split() print(c[0])
When I run the code, the output is just the 'a'. I have no idea why this is happening. Do you?
I'm working on a book I've downloaded from project Guttenberg and after doing some data cleaning I have ended up with a list of strings. Next I should split each string into words and collect all the words in a new list.
I have tried to use the split commando but somehow I end up with transforming each string into a list instead of a a string.
I'm sorry if I'm being vague. Please let me know if I should provide more infromation...
I have created the following function.
def splitter():
wordList = [s.split(" ") for s in book]
return wordList
book = splitter()
Somehow I end up with the following output when I type book[0] into the console:
['the',
'history',
'of',
'australian',
'exploration',
'from',
'1788',
'to',
'1888']
Instead of splitting the string and ending up with a list of strings I have created a list of lists.
What I want to end up with is:
In[] book[0]
Out[] the
and
in[] book[:9]
['the',
'history',
'of',
'australian',
'exploration',
'from',
'1788',
'to',
'1888']