python 字符串处理函数(二)
本帖最后由 素简生香 于 2017-11-17 11:22 编辑string = 'hellO BoWeiFeng'# 0. 字串长度:len(string)print '%s length=%d' % (string,len(string)) # 3. 字符串查找相关# 搜索指定字符串,没有返回-1:string.find('e')# 指定起始位置搜索:string.find('e',start)# 指定起始及结束位置搜索:string.find('e',start,end)# 从右边开始查找:string.rfind('e')# 统计搜到多少个指定字符串:string.count('e') print '%s find llo=%d' % (string,string.find('llo'))print '%s find e=%d' % (string,string.find('e'))print '%s find e from %d=%d' % (string,1,string.find('e',1))print '%s find e from %d to %d=%d' % (string,1,2,string.find('e',1,2))print '%s rfind e=%d' % (string,string.rfind('e'))print '%s count e=%d' % (string,string.count('e')) # 上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1print '%s index llo ' % (string,string.index('llo',1,2)) # 4. 字符串替换相关# 替换old为new:string.replace('old','new')# 替换指定次数的old为new:string.replace('old','new',maxReplaceTimes)print '%s replace t to *=%s' % (string,string.replace('e', '*'))print '%s replace t to *=%s' % (string,string.replace('e', '*',1))# 字符串去空格 及去指定字符 # 去两边空格:string.strip() # 去左空格:string.lstrip() # 去右空格:string.rstrip() # 去两边字符串:string.strip('d'),相应的也有lstrip,rstripstring=' python String function 'print '%s strip=%s' % (string,string.strip())string='python String function'print '%s strip=%s' % (string,string.strip('d')) # 5. 按指定字符分割字符串为数组(默认按空格分隔):string.split(' ')string='a b c de'print '%s strip=%s' % (string,string.split())string='a-b-c-de'print '%s strip=%s' % (string,string.split('-')) # 6. 字符串判断# 是否以start开头:string.startswith('start')# 是否以end结尾:string.endswith('end')# 是否全为字母或数字:string.isalnum()# 是否全字母:string.isalpha()# 是否全数字:string.isdigit()# 是否全小写:string.islower()# 是否全大写:string.isupper()string='python String function'print '%s startwith t=%s' % (string,string.startswith('t'))print '%s endwith d=%s' % (string,string.endswith('d'))print '%s isalnum=%s' % (string,string.isalnum())string='pythonStringfunction'print '%s isalnum=%s' % (string,string.isalnum())print '%s isalpha=%s' % (string,string.isalpha())print '%s isupper=%s' % (string,string.isupper())print '%s islower=%s' % (string,string.islower())print '%s isdigit=%s' % (string,string.isdigit())string='5123'print '%s isdigit=%s' % (string,string.isdigit())
页:
[1]