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 "".
How to Convert a String to a List of Words. Another way to convert a string to a list is by using the split() Python method. The split() method splits a string into a list, where each list item is each word that makes up the string. Each word will be an individual list item.
To convert a string in a list of words, you just need to split it on whitespace. You can use split() from the string class. The default delimiter for this method is whitespace, i.e., when called on a string, it'll split that string at whitespace characters.
Use the list() class to split a word into a list of letters, e.g. my_list = list(my_str) . The list() class will convert the string into a list of letters. Copied!
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
>>> s = "foobar"
>>> list(s)
['f', 'o', 'o', 'b', 'a', 'r']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With