split
先help一下
>>> help(str.split)
Help on method_descriptor:
split(...)
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.
再翻译一下
S.split(sep=None, maxsplit=-1) 返回的是字符串列表, 里面有两个参数:sep和maxsplit
sep 用来指定用来拆分字符串的分隔符, 默认为None(以空白字符串为分隔符)
maxsplit 用来指定最大分隔数, 不指定则分隔所有
看代码:
>>> str = "the different about split and splitlines is ..."
>>> print (str.split( ))
['the', 'different', 'about', 'split', 'and', 'splitlines', 'is', '...']
>>> print (str.split('i'))
['the d', 'fferent about spl', 't and spl', 'tl', 'nes ', 's ...']
>>> print (str.split('i', 1))
['the d', 'fferent bout split and splitlines is ...']
splitlines
还是先help一下
>>> help(str.splitlines)
Help on method_descriptor:
splitlines(...)
S.splitlines([keepends]) -> list of strings
Return a list of the lines in S, breaking at line boundaries.
Line breaks are not included in the resulting list unless keepends
is given and true.
S.splitlines([keepends]) 返回的也是个字符串列表, 不过分隔符为(’\r’, ‘\r\n’, \n’),也就是说按照行分隔,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
看代码
>>> str1 = 'ab c\n\nde fg\rkl\r\n'
>>> str1.splitlines()
['ab c', '', 'de fg', 'kl']
>>> str1.splitlines(True)
['ab c\n', '\n', 'de fg\r', 'kl\r\n']
>>>
完事儿 . . .