W3docs

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:

Here is an example of how to split a string into a list of words in Python:

Split a string into a list of all characters in Python

python— editable, runs on the server

This will output:


['This', 'is', 'an', 'example', 'string.']

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:

Split a string by regular expressions in Python

python— editable, runs on the server

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.

Split a string by the shlex module in Python

python— editable, runs on the server

This will output:


['This', 'is', 'an', 'example string']