Python字符串split学习一(自定义字符串拆分)
2013-09-20 20:44
465 查看
开始学习python,第二天,尽管python内建函数split已经能干很多事情,但是遇到这种情况就要自己定义函数了:
string = ' wang__chuang_____bo '
#coding=utf-8 #string split #author wangchuanbo #time 2013-09-20 s = '&aa ab ac ad&' #去掉字符串开头和结尾的指定字符 s1 = s.strip('&') print s1 #步骤一:先找第一个单词 a = s1.find(" ") word1 = s1[:a] print 'the first word is:',word1 #步骤二:找第二个单词 while s1[a] == " ": a = a + 1 b = s1.find(" ",a) word2 = s1[a:b] print 'the second word is:',word2 #自定义的拆分方法 #string:要拆分的字符串,delimiter:分隔符,begin_end:字符串开始和结尾标识符 def my_split(string,delimiter,begin_end=" "): string = string.strip(begin_end) a = string.find(delimiter) first_word = string[:a] result = [] result.append(first_word) b = a while b <= len(string) and b != -1: while string[a] == delimiter: a = a + 1 b = string.find(delimiter,a) if b != -1: res = string[a:b] else: res = string[a:] a = b result.append(res) return result s1 = '&adfs sdfjklsj dd de&' #如果仅是拆除空格s1.split()可以搞定 print my_split(s1," ","&") s2 = ' jkj**jkjk*jkkk****d ' print my_split(s2,"*") s3 = ' wang__chuan_____bo ' print my_split(s3,'_') s4 = ' wang..xiao.....yuan ' print my_split(s4,'.')
相关文章推荐
- python 4-1 如何拆分含有多种分隔符的字符串re.split()/str.split()
- Python的字符串和拆分方法join、split
- Python的字符串连接join和拆分split
- 基于《PythonCookbook》的学习(1)——针对任意多的分隔符拆分字符串
- Python split() 函数 拆分字符串 将字符串转化为列
- python中字符串拆分与合并(split()和join())
- Python split() 函数 拆分字符串 将字符串转化为列
- python拆分字符串(.split),以及连接字符串(.join)。
- Python split() 函数 拆分字符串 将字符串转化为列
- python split()函数使用拆分字符串 将字符串转化为列表
- sqlserver字符串拆分(split)方法汇总(转载并仔细学习)
- python学习(四)字符串学习
- [Python学习] 模块三.基本字符串
- python学习第二天:数字与字符串转换及逻辑值
- Python学习笔记ucas(lecture2)数据结构(字符串、列表、元组、字典、集合)
- Python学习笔记三 字符串
- python 字符串split的用法分享
- Python 3.2 字符串方法学习总结
- Python学习笔记_字符串类型内建方法
- 【Python学习笔记】字符串和编码