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
www.chinagame.me
www.quanzhan.org"

In [9]: print u.splitlines()
['www.jeapedu.com', 'www.chinagame.me', 'www.quanzhan.org']
    这个样例不好。由于用split(' ')也能够切割成上面的结果。

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

In [14]: print u.split("
")
['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,意思是不保留每行结尾的 , 而keepends为True时。切割的每一行里尾部会有 。

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




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

原文地址:https://www.cnblogs.com/mqxnongmin/p/10535272.html