How do I split a string into a list of words?
Here is an example of how to split a string into a list of words in Python:
This will output:
['This', 'is', 'an', 'example', 'string.']
Watch a video course
Python - The Practical Guide
Alternatively, you can use the re
module to split a string using a regular expression. Here is an example that uses the re.split()
function to split a string into a list of words:
import re
string = "This is an example string."
word_list = re.split(r'\W+', string)
print(word_list)
This will output:
['This', 'is', 'an', 'example', 'string', '']
You can also use split()
method from shlex
module which is more advanced than split()
and re.split()
and also support string which contains quotes.
import shlex
string = 'This is an "example string"'
word_list = shlex.split(string)
print(word_list)
This will output:
['This', 'is', 'an', 'example string']