Python: str.split () - can only the "limit" parameter be specified?

I want to split the string into whitespaces (the default behavior) , but I want it to split it only once - Ie I want it to return an array with no more than 2 elements.

If this is not possible, i.e. if, to indicate the restriction, I must also specify a template - could you tell me how to specify the default value?

+4
source share
4 answers

It works:

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

Document:

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

Returns a list of words in S, using sep as a separator string. If maxsplit is specified, maximum maxsplit is broken. If sep is not specified or None, the whitespace line is a separator, and empty lines are removed from the result.

In interactive mode, you should learn:

 >>> help('a'.split) 

In IPython, just use the question mark:

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

I would suggest using IPython and especially Notebook. This makes such a study much more convenient.

+13
source

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

 str.split(None, maxsplit) 

S.split ([sep [, maxsplit]]) β†’ list of lines

Returns a list of words in string S, using sep as a separator string. If maxsplit is specified, maximum maxsplit is broken. If sep is not specified or None, the whitespace line is a delimiter, and empty lines are removed from the result.

+3
source

split() has a second parameter that does just that.

 string = "abc" print string.split(' ', 1) >> ['a', 'b c'] 
0
source

Breaks the string into sequential whitespace † in most cases maxsplit ††

† The resulting list will not contain leading or trailing blank lines ( "" ) if the string has leading or trailing spaces
†† Distributions are made from left to right. To split another path (from right to left), use str. r split() str. r split() The str. r split() method str. r split() str. r split() (requires Python 2.4+)


Python 2

str. split (sep[, maxsplit]])

Use str.split(None, maxsplit)

Note :
Specifying sep as None ≝ without 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']
0
source

All Articles