python裡的splitlines詳解

來源:互聯網
上載者:User

    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是按行分割字串,返回值也是個列表。




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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.