python里的splitlines详解

    Python的split方法函数可以分割字符串成列表,默认是以空格作为分隔符sep来分割字符串。

In [1]: s = "www jeapedu com"

In [2]: print s.split()
['www', 'jeapedu', 'com']

    当然可以改变sep分割字符串为其他字符串。

In [6]: t = "www.jeapedu.com"

In [7]: print t.split(".")
['www', 'jeapedu', 'com']


    python的字符串类里还提供了splitlines方法函数。

splitlines(...)
    S.splitlines(keepends=False) -> 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.
    splitlines函数什么意思呢?

In [8]: u = "www.jeapedu.com\nwww.chinagame.me\nwww.quanzhan.org"

In [9]: print u.splitlines()
['www.jeapedu.com', 'www.chinagame.me', 'www.quanzhan.org']
    这个例子不好,因为用split('\n')也可以分割成上面的结果。

In [13]: u = "www.jeapedu.com\nwww.chinagame.me\nwww.quanzhan.org"

In [14]: print u.split("\n")
['www.jeapedu.com', 'www.chinagame.me', 'www.quanzhan.org']
    结果一样,但是下面的测试用例就必须用splitlines了。

t =  """www.jeapedu.com
       www.chinagame.me
       www.quanzhan.org
     """
    print t.splitlines()

     程序结果如下所示:

['www.jeapedu.com', '       www.chinagame.me', '   www.quanzhan.org']

       结果不太好,用strip函数去掉字符串前后的空格。

   好,至此splitlines的基本使用已经解析完成,那splitlines里的参数keepends又是什么意思呢?

t =  """www.jeapedu.com
       www.chinagame.me
       www.quanzhan.org
     """
print t.splitlines()
print t.splitlines(True)
    默认splitelines参数keepends为False,意思是不保留每行结尾的\n, 而keepends为True时,分割的每 一行里尾部会有\n。

    总结,splitlines是按行分割字符串,返回值也是个列表。




-----------------------------------------------------------

  • 42
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值