How to convert a string to a list of words in python?

PythonServer Side ProgrammingProgramming

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.

For example

>>> "Please split this string".split()
['Please', 'split', 'this', 'string']

Regex can also be used to solve this problem. You can call the re.split() method using the regex '\s+' as delimiter. Note that this method is slower than the above method.

>>> import re
>>> re.split('\s+', 'Please split this string')
['Please', 'split', 'this', 'string']
raja
Updated on 17-Dec-2019 06:42:15

Advertisements