split() Function basic format :
split(sep=None, maxsplit=-1)
Returns a list of words in a string , Use sep As a separate string .
If given maxsplit, At most maxsplit Sub resolution ( therefore , The list will have at most maxsplit+1 Elements ).
If maxsplit Not specified or is -1, The number of splits is not limited ( Make all possible splits ).
seq
The delimited string defaults to None,maxsplit
The default indicates that the number of splits is not limited .split()
Return to one list
situation 1: to `sep``: basis sep Split all strings
'a.bc'.split('.')
['a', 'bc']
situation 2: to sep
, to maxsplit
: basis sep
For strings, follow maxsplit
Value of to split
'a.b.c'.split('.',maxsplit=1)
['a', 'b.c']
situation 3: If sep
Not specified or is None
: Consecutive spaces are treated as a single separator , The result will not contain an empty string at the beginning or end , If the string contains prefix or suffix spaces .
'1 2 3'.split()
#['1', '2', '3']
'1 2 3'.split(maxsplit=1)
#['1', '2 3']
' 1 2 3 '.split()
#['1', '2', '3']
situation 4: Handle consecutive delimiters : Consecutive delimiters are not grouped together but are treated as Separate empty strings
'a.b..c'.split('.')
['a', 'b', '', 'c']
rsplit() The basic format :
rsplit(sep=None, maxsplit=- 1)
Returns a list of words in a string , Use sep As a separate string .
If given maxsplit, At most maxsplit Sub resolution , from Far right Start .
And split() function
The difference between :rsplit()
from Far right Start splitting rsplit()
The rest of the actions and split()
identical
splitlines() The basic format :
splitlines(keepends=False)
Returns a list of lines in the original string , Split at the line boundary .
The result list does not contain row boundaries , Unless you give keepends And it's true .
situation 1: Default splitlines()
'ab c\n\nde fg\rkl\r\n'.splitlines()
#['ab c', '', 'de fg', 'kl']
situation 2: Include row boundaries keepends = True
'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
#['ab c\n', '\n', 'de fg\r', 'kl\r\n']
When a delimited string is given sep
when , For an empty string, this method returns an empty list ; A newline at the end does not add extra lines to the result .
"".splitlines()
#[]
"One line\n".splitlines()
#['One line']
As a comparison ,split('\n')
As the result of the :
''.split('\n')
#['']
'Two lines\n'.split('\n')
#['Two lines', '']
Built in type -split:https://docs.python.org/zh-cn/3/library/stdtypes.html?highlight=split