Split string on whitespace in Python


Question

I'm looking for the Python equivalent of

String str = "many   fancy word \nhello    \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);

["many", "fancy", "word", "hello", "hi"]
1
396
3/21/2015 11:25:25 PM

Accepted Answer

The str.split() method without an argument splits on whitespace:

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
726
11/13/2011 6:46:54 PM

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon