python中split()的用法

Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则仅分隔 num 个子字符串。

语法:

str.split(str="", num=string.count(str))
  • str -- 分隔符,默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等。
  • num -- 分割次数。(如num=1,则表示分割1次或者说在第一个str处进行分割)

例子:

1 str = "Line1-abcdef \nLine2-abc \nLine4-abcd"
2 print(str.split( ))
3 >>>['Line1-abcdef', 'Line2-abc', 'Line4-abcd']
4 print(str.split(' ', 1 ))
5 >>>['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
6 print(str.split(' ', 2 ))
7 >>>['Line1-abcdef', '\nLine2-abc', '\nLine4-abcd']
8 print(str.split(' ', 3 ))
9 >>>['Line1-abcdef', '\nLine2-abc', '\nLine4-abcd']

 

posted @ 2018-10-19 15:15  sen_c7  阅读(1263)  评论(0编辑  收藏  举报