The Python Oracle

Split string on whitespace in Python

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping

--

Chapters
00:00 Question
00:20 Accepted answer (Score 1145)
00:36 Answer 2 (Score 85)
00:46 Answer 3 (Score 28)
01:09 Answer 4 (Score 22)
01:35 Thank you

--

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

Accepted answer links:
[str.split()]: https://docs.python.org/3/library/stdtyp...

--

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.