本文共 2180 字,大约阅读时间需要 7 分钟。
12、字符串的分割和组合
12.1 str.split():字符串分割函数
通过指定分隔符对字符串进行切片,并返回分割后的字符串列表。 语法: str.split(s, num)[n] 参数说明: s:表示指定的分隔符,不写的话,默认是空格(’ ‘)。如果字符串中没有给定的分隔符时,则把整个字符串作为列表的一个元素返回。 num:表示分割次数。如果指定了参数num,就会将字符串分割成num+1个子字符串,并且每一个子字符串可以赋给新的变量。 [n]:表示选取第n个分片,n表示返回的list中元素下标,从0开始的。12.2 os.path.split():路径文件分割函数
按照路径将文件名和路劲分割开,这里需要引入os包(import os)。 语法: os.path.split(‘PATH’) 参数说明: PATH指一个文件所在的绝对路劲 实例: 1)、split()函数常用的一些实例#定义一个字符串str1>>> str1 = "3w.gorly.test.com.cn"#使用默认分隔符分割字符串str1>>> print str1.split()['3w.gorly.test.com.cn']#指定分隔符为'.',进行分割字符串str1>>> print str1.split('.')['3w', 'gorly', 'test', 'com', 'cn']#指定分隔符为'.',并且指定切割次数为0次>>> print str1.split('.',0)['3w.gorly.test.com.cn']#指定分隔符为'.',并且指定切割次数为1次>>> print str1.split('.',1)['3w', 'gorly.test.com.cn']#指定分隔符为'.',并且指定切割次数为2次>>> print str1.split('.',2)['3w', 'gorly', 'test.com.cn']#这种分割等价于不指定分割次数str1.split('.')情况>>> print str1.split('.',-1)['3w', 'gorly', 'test', 'com', 'cn']#指定分隔符为'.',并取序列下标为0的项>>> print str1.split('.')[0]3w#指定分隔符为'.',并取序列下标为4的项>>> print str1.split('.')[4]cn
2)、统计字符串中出现的单词个数
>>> str2 = "This is the voa special english health report">>> list1 = str2.split(' ')>>> list1['This', 'is', 'the', 'voa', 'special', 'english', 'health', 'report']>>> len(list1)8
3)、多次连续使用split()函数
例如:将从html代码中提取网站地址>>> s = 'test'>>> print s.split('"')[1]www.test.com>>> print s.split('"')[1].split('.')['www', 'test', 'com']
4)、使用split()函数去除一些特殊字符
#去掉字符串中的换行符\n>>> str2 = '''hello... world... !'''>>> str2.split('\n')['hello', 'world', '!']
5)、分割文件和其路劲
>>> import os>>> print os.path.split("d:\test\a.txt")('d:', '\test\x07.txt')>>> print os.path.split('d:/test/a.txt')('d:/test', 'a.txt')>>> print os.path.split('d:\\test\\a.txt')('d:\\test', 'a.txt')
从上面的结果可以看出,如果我们路劲写成d:\test\a.txt,是得不到我们想要的结果,必须将再加一个’\’来转义第二个’\’才行,或者直接写成d:/test/a.txt这样。
12.3 str.join(seq):将序列组合成字符串函数
语法:s.join(seq) 参数说明: s:给定的连接符 seq:代表要连接的序列,如list、tuple、str的序列 实例: 1)、普通字符串的连接(只能针对字符或字符串进行连接)>>> '-'.join("abdcd")'a-b-d-c-d'>>> list1 = ['a','b','c']>>> ''.join(list1)'abc'
2)、字符串分割函数和字符串组合函数组合使用的情况
>>> s = 'test'>>> print s.split('"')[1]www.test.com>>> print s.split('"')[1].split('.')['www', 'test', 'com']>>> print '.'.join(s.split('"')[1].split('.'))www.test.com
转载地址:http://ebmdi.baihongyu.com/