I want to split a string on whitespaces (default behavior), but I want it to split it only once - I.e. I want it to return an array with 2 items at most.
If it is not possible - i.e. if for specifying the limit I have to also specify the pattern - could you please tell how to specify the default one?
Splitting the String by Passing the Maxsplit Parameter. The maximum number of splits that a split() function can perform on a given string or line can be specified using the maxsplit parameter and passed as an argument to the split() function.
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
split() method accepts two arguments. The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
† 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+)
Use
str.split(sep[, maxsplit]])
str.split(None, maxsplit)
Note:
Specifyingsep
asNone
≝ not specifyingsep
str.split(None, -1)
≝str.split()
≝str.split(None)
Option A: Stick with positional arguments (Python 2 option):
str.split(sep=None, maxsplit=-1)
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With