Python七天学习之Day06(1)——字符串处理方法全集

Python七天学习之Day06(1)——字符串处理方法全集

字符串

字母处理
全部大写:str.upper()
print ‘%s lower=%s’ % (str,str.lower())
全部小写:str.lower()
print ‘%s upper=%s’ % (str,str.upper())
大小写互换:str.swapcase()
print ‘%s swapcase=%s’ % (str,str.swapcase())
首字母大写,其余小写:str.capitalize()
print ‘%s capitalize=%s’ % (str,str.capitalize())
首字母大写:str.title()
print ‘%s title=%s’ % (str,str.title())

格式化相关
获取固定长度,右对齐,左边不够用空格补齐:str.ljust(width)
print ‘%s ljust=%s’ % (str,str.ljust(20))
获取固定长度,左对齐,右边不够用空格补齐:str.ljust(width)
print ‘%s rjust=%s’ % (str,str.rjust(20))
获取固定长度,中间对齐,两边不够用空格补齐:str.ljust(width)
print ‘%s center=%s’ % (str,str.center(20))
获取固定长度,右对齐,左边不足用0补齐
print ‘%s zfill=%s’ % (str,str.zfill(20))

字符串搜索相关
搜索指定字符串,没有返回-1:str.find(‘t’)
print ‘%s find nono=%d’ % (str,str.find(‘nono’))
指定起始位置搜索:str.find(‘t’,start)
print ‘%s find t=%d’ % (str,str.find(‘t’))
指定起始及结束位置搜索:str.find(‘t’,start,end)
print ‘%s find t from %d=%d’ % (str,1,str.find(‘t’,1))
从右边开始查找:str.rfind(‘t’)
print ‘%s find t from %d to %d=%d’ % (str,1,2,str.find(‘t’,1,2))
#print '%s index nono ’ % (str,str.index(‘nono’,1,2))
搜索到多少个指定字符串:str.count(‘t’)
print ‘%s rfind t=%d’ % (str,str.rfind(‘t’))
上面所有方法都可用index代替,不同的是使用index查找不到会抛异常,而find返回-1
print ‘%s count t=%d’ % (str,str.count(‘t’))

字符串替换相关
替换old为new:str.replace(‘old’,‘new’)
print ‘%s replace t to =%s’ % (str,str.replace(‘t’, '’))
替换指定次数的old为new:str.replace(‘old’,‘new’,maxReplaceTimes)
print ‘%s replace t to =%s’ % (str,str.replace(‘t’, '’,1))

字符串去空格及去指定字符
去两边空格:str.strip()
str=’ python String function ’
print ‘%s strip=%s’ % (str,str.strip())
去左空格:str.lstrip()
去右空格:str.rstrip()
去两边字符串:str.strip(‘d’),相应的也有lstrip,rstrip
str=‘python String function’
print ‘%s strip=%s’ % (str,str.strip(‘d’))

按指定字符分割字符串为数组:str.split(’ ‘)
默认按空格分隔
str=‘a b c de’
print ‘%s strip=%s’ % (str,str.split())
str=‘a-b-c-de’
print ‘%s strip=%s’ % (str,str.split(’-’))

字符串判断相关
str=‘python String function’
是否以start开头:str.startswith(‘start’)
print ‘%s startwith t=%s’ % (str,str.startswith(‘t’))
是否以end结尾:str.endswith(‘end’)
print ‘%s endwith d=%s’ % (str,str.endswith(‘d’))
是否全为字母或数字:str.isalnum()
print ‘%s isalnum=%s’ % (str,str.isalnum())

str=‘pythonStringfunction’
是否全字母:str.isalpha()
print ‘%s isalpha=%s’ % (str,str.isalpha())
print ‘%s isalnum=%s’ % (str,str.isalnum())
是否全数字:str.isdigit()
print ‘%s isdigit=%s’ % (str,str.isdigit())
str=‘3423’
print ‘%s isdigit=%s’ % (str,str.isdigit())
是否全小写:str.islower()
print ‘%s islower=%s’ % (str,str.islower())
是否全大写:str.isupper()
print ‘%s isupper=%s’ % (str,str.isupper())

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值