Computer >> Computer tutorials >  >> Programming >> Python

How to split string on whitespace in Python?


You can usesplit() 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']