regex – Split string on whitespace in Python

regex – Split string on whitespace in Python

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

>>> many   fancy word nhello    thi.split()
[many, fancy, word, hello, hi]
import re
s = many   fancy word nhello    thi
re.split(s+, s)

regex – Split string on whitespace in Python

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

Its 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]

Leave a Reply

Your email address will not be published. Required fields are marked *