Python: str.split() - is it possible to only specify the "limit" parameter?

Split string on consecutive whitespace at most maxsplit times††

Resulting list will contain no leading or trailing empty strings ("") if the string has leading or trailing whitespace
†† Splits are made left to right. To split the other way (right to left), use the str.rsplit() method (requires Python 2.4+)


Python 2

str.split(sep[, maxsplit]])

Use str.split(None, maxsplit)

Note:
Specifying sep as None not specifying sep

str.split(None, -1) str.split() str.split(None)


Python 3

str.split(sep=None, maxsplit=-1)

Option A: Stick with positional arguments (Python 2 option): str.split(None, maxsplit)
>>> ' 4 2 0 '.split(None, 420)
['4', '2', '0']

Option B (personal preference, using keyword arguments): str.split(maxsplit=maxsplit)

>>> ' 4 2 0 '.split(maxsplit=420)` 
['4', '2', '0']

This works:

>>> 'a b c'.split(None, 1)
['a', 'b c']

The docstring:

S.split(sep=None, maxsplit=-1) -> list of strings

Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

You should explore at the interactive prompt:

>>> help('a'.split)

In IPython just use a question mark:

In [1]:  s = 'a'
In [2]:  s.split?

I would suggest using IPython and especially the Notebook. This makes this kind of exploration much more convenient.


If you specify None as a separator, you'll get the default behavior:

str.split(None, maxsplit)

S.split([sep [,maxsplit]]) -> list of strings

Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.

Tags:

Python

String