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