split()

函数:split()

def split(self, sep=None, maxsplit=-1)
S.split(sep=None, maxsplit=-1) -> list of strings
                    字符串列表
Return a list of the words in S, using sep as the delimiter string.
   返回S中的单词列表,使用sep作为分隔符字符串。
If maxsplit is given, at most maxsplit splits are done.
   如果maxsplit被给予,那么大多数的maxsplit分割就完成了。
If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
   如果sep没有指定或者没有,任何空白字符串都是分隔符,并且从结果中删除空字符串。
"""
return []

Python中有split()和os.path.split()两个函数,具体作用如下:
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(list)
os.path.split():按照路径将文件名和路径分割开

一、函数说明
1、split()函数
语法:str.split(str="",num=string.count(str))[n]

参数说明:
str:   表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]:   表示选取第n个分片

注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略

2、os.path.split()函数
语法:os.path.split('PATH')

参数说明:

  1. PATH指一个文件的全路径作为参数:
  2. 如果给出的是一个目录和文件名,则输出路径和文件名
  3. 如果给出的是一个目录名,则输出路径和为空文件名


二、实例
1、常用实例

 1 >>> u = "www.doiido.com.cn"
 2   
 3 #使用默认分隔符
 4 >>> print u.split()
 5 ['www.doiido.com.cn']
 6   
 7 #以"."为分隔符
 8 >>> print u.split('.')
 9 ['www', 'doiido', 'com', 'cn']
10   
11 #分割0次
12 >>> print u.split('.',0)
13 ['www.doiido.com.cn']
14   
15 #分割一次
16 >>> print u.split('.',1)
17 ['www', 'doiido.com.cn']
18   
19 #分割两次
20 >>> print u.split('.',2)
21 ['www', 'doiido', 'com.cn']
22   
23 #分割两次,并取序列为1的项
24 >>> print u.split('.',2)[1]
25 doiido
26   
27 #分割最多次(实际与不加num参数相同)
28 >>> print u.split('.',-1)
29 ['www', 'doiido', 'com', 'cn']
30   
31 #分割两次,并把分割后的三个部分保存到三个文件
32 >>> u1,u2,u3 = u.split('.',2)
33 >>> print u1
34 www
35 >>> print u2
36 doiido
37 >>> print u3
38 com.cn
39  

2、去掉换行符

 1 >>> c = '''say
 2 hello
 3 baby'''
 4   
 5 >>> print c
 6 say
 7 hello
 8 baby
 9   
10 >>> print c.split('
')
11 ['say', 'hello', 'baby']

3、分离文件名和路径

 1 1
 2 2
 3 3
 4 4
 5 5
 6  
 7 >>> import os
 8 >>> print os.path.split('/dodo/soft/python/')
 9 ('/dodo/soft/python', '')
10 >>> print os.path.split('/dodo/soft/python')
11 ('/dodo/soft', 'python')
12  

4、一个超级好的例子

1 >>> str="hello boy<[www.doiido.com]>byebye"
2   
3 >>> print str.split("[")[1].split("]")[0]
4 www.doiido.com
5   
6 >>> print str.split("[")[1].split("]")[0].split(".")
7 ['www', 'doiido', 'com']

 5、通过re模块的split()方法

 1 def mySplit(s,ds):
 2     res =[s]
 3     for d in ds:
 4         t =[]
 5         map(lambda x:t.extend(x.split(d)),res)
 6         res = t
 7     #当s中存在连续的分隔符时,就会出现空格的,下面是去除空格
 8     return [x for x in res if x]
 9 s = "abcd,1313|;gg2*hhh"
10 res = ',|;*'
11 print(mySplit(s,res))
原文地址:https://www.cnblogs.com/smurfs/p/9643035.html