Python split和splitlines区别

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']
>>>

完事儿 . . .

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值