The Python Oracle

Split string on whitespace in Python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Split String On Whitespace In Python
00:12 Accepted Answer Score 1204
00:26 Answer 2 Score 91
00:32 Answer 3 Score 22
00:50 Answer 4 Score 31
01:07 Thank you

--

Full question
https://stackoverflow.com/questions/8113...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #regex #string #split #whitespace

#avk47



ACCEPTED ANSWER

Score 1204


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

>>> "many   fancy word \nhello    \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']



ANSWER 2

Score 91


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



ANSWER 3

Score 31


Using split() will be the most Pythonic way of splitting on a string.

It's also useful to remember that if you use split() on a string that does not have a whitespace then that string will be returned to you in a list.

Example:

>>> "ark".split()
['ark']



ANSWER 4

Score 22


Another method through re module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

Above regex would match one or more non-space characters.