Python内置的字符串处理方法
注:字符串对象是不可变的,所以字符串对象提供的涉及字符串“修改”的方法都是返回修改之后的新字符串,并不对原字符串做任何修改。
一、字符串查找类方法
①find()和rfind()方法
find()和rfind()方法分别用来查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次和最后一次出现的位置,如果不存在则返回-1。
s = "bird,fish,monkey,rabbit"
s.find("fish") #5
s.find('b') #0
s.rfind('b') #20
s.find('tiger') #指定字符串不存在,为-1.
②index和rindex()方法
index()和rindex()方法分别用来查找一个字符串在另一个字符串指定范围(默认是整个字符串)中首次和最后一次出现的位置,如果不存在则抛出异常。
s = "bird,fish,monkey,rabbit"
s.index('bird') #0
s.rindex('i') #21
s.index('tiger') #指定字符串不存在时抛出异常:
#ValueError: substring not found
③count()方法
count()方法用来返回一个字符串在另一个字符串中出现的次数,如果不存在则返回0。
s = "bird,fish,monkey,rabbit"
s.count('bird') #1
s.count('b') #3
s.count('tiger') #指定字符串不存在,0
二、字符串分隔类方法
①split()和rsplit()方法
split()和rsplit()方法分别用来以指定字符为分隔符,从原字符串左端和右端开始将其分隔成多个字符串,并返回包含分隔结果的列表。
s = "bird,fish,monkey,rabbit"
s.split(',') # 按‘,’分隔字符串['bird', 'fish', 'monkey', 'rabbit']
s = 'I am a boy'
s.split() #['I', 'am', 'a', 'boy']
#默认按空白符号分隔字符串,包括空格、换行符、制表符
s.rsplit() #['I', 'am', 'a', 'boy']
split()和rsplit()方法可以指定最大分隔次数
s = "南京 上海 天津 杭州 无锡"
s.split(maxsplit=2) #从左开始,最多分隔2次,分出“南京”和“上海”
#['南京', '上海', '天津 杭州 无锡']
s.rsplit(maxsplit=2) #从右开始,最多分隔2次,分出“杭州”和“无锡”
#['南京 上海 天津', '杭州', '无锡']
利用re模块分割含有多种分割符的字符串:
import re
a='Beautiful, is; better*than\nugly'
# 四个分隔符为:, ; * \n
x= re.split(',|; |\*|\n',a)
print(x)
#['Beautiful', ' is', 'better', 'than', 'ugly']
网址地址解析
str="http://www.runoob.com/python/att-string-split.html"
print("0:%s"%str.split("/")[-1])
print("1:%s"%str.split("/")[-2])
print("2:%s"%str.split("/")[-3])
print("3:%s"%str.split("/")[-4])
print("4:%s"%str.split("/")[-5])
print("5:%s"%str.split("/",-1))
print("6:%s"%str.split("/",0))
print("7:%s"%str.split("/",1))
print("8:%s"%str.split("/",2))
print("9:%s"%str.split("/",3))
print("10:%s"%str.split("/",4))
print("11:%s"%str.split("/",5))
#0:att-string-split.html
#1:python
#2:www.runoob.com
#3:
#4:http:
#5:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
#6:['http://www.runoob.com/python/att-string-split.html']
#7:['http:', '/www.runoob.com/python/att-string-split.html']
#8:['http:', '', 'www.runoob.com/python/att-string-split.html']
#9:['http:', '', 'www.runoob.com', 'python/att-string-split.html']
#10:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
#11:['http:', '', 'www.runoob.com', 'python', 'att-string-split.html']
②partition()和rpartition()方法
partition()和rpartition()方法分别用来以指定字符串为分隔符将原字符串分隔为3个部分,即分隔符之前的字符串、分隔符字符串和分隔符之后的字符串。如果指定的字符串不在原字符串中,则返回原字符串和两个空字符串。如果字符串中有多个分隔符,那么partition()方法按从左向右遇到的第一个分隔符来进行分隔,rpartition()方法按从右向左遇到的第一个分隔符来进行分隔,返回一个元组。
s = "bird,fish,monkey,fish,rabbit"
s.partition('fish') #按左端第一个fish将字符串分成3个部分
#('bird,', 'fish', ',monkey,fish,rabbit')
s.rpartition('fish') #按右端第一个fish将字符串分成3个部分
#('bird,fish,monkey,', 'fish', ',rabbit')
s.partition('tiger') #分隔符不存在,则返回原字符串和两个空字符串
#('bird,fish,monkey,fish,rabbit', '', '')
s.partition(',') #('bird', ',', 'fish,monkey,fish,rabbit')
三、字符串连接方法
①join()方法
join() 法用于将序列中的元素以指定的字符连接生成一个新的字符串。
li = ['apple','banana','pear','peach']
':'.join(li) #'apple:banana:pear:peach' 用:作为连接符
'-'.join(li) #'apple-banana-pear-peach' 用-作为连接符
seq = {'hello':'nihao','good':2,'boy':3,'doiido':4}
'-'.join(seq) #'hello-good-boy-doiido'字典只对键进行连接
''.join([1,2,3,4]) #TypeError: sequence item 0: expected str instance, int found 列表中的元素也需要是字符串
','.join(['1','2','3','4']) #'1,2,3,4'
四、大小写字符转换方法
lower()方法用来将字符串转换为小写字符串;upper()方法用来将字符串转换为大写字符串;capitalize()方法用来将字符串首字母变为大写;title()方法用来将字符串中每个单词的首字母变为大写;swapcase()方法用来将字符串中的字符大小写互换。
s = "I hava two big eyes."
s.lower() #返回小写字符串'i hava two big eyes.'
s.upper() #返回大写字符串'I HAVA TWO BIG EYES.'
s.capitalize() #首字母大写'I hava two big eyes.'
s.title() #每个单词首字母大写'I Hava Two Big Eyes.'
s.swapcase() #大小写互换'i HAVA TWO BIG EYES.'
五、字符串替换方法
①replace()方法
replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
s = "你是我的小呀小苹果儿"
s.replace("小","small") # '你是我的small呀small苹果儿'
str = "this is string example isa isb....wow!!!"
str.replace("is", "was", 3)
#'thwas was string example wasa isb....wow!!!'
六、删除字符串两端、右端、左端连续空白字符和指定字符方法
①strip()、rstrip()、lstrip()方法
s = " abc "
s.strip() #删除两端空白字符 'abc'
s.rstrip() #删除右端空白字符' abc'
s.lstrip() #删除左端空白字符'abc '
s = '=====Mike====='
s.strip('=') #删除两端指定字符"=",'Mike'
s.rstrip('=') #删除右端指定字符“=” '=====Mike'
s.lstrip('=') #删除左端指定字符“=” 'Mike====='
七、判断字符串是否以指定字符开始或结束方法
①startswith()和endswith()
s="Python程序设计.py"
s.startswith("Python") #检测字符串是否以“Python”开始 返回True
s.endswith("py") #检测字符串是否以“py”结束 返回True
八、字符串排版方法
center()、ljust()、rjust()、zfill()方法
s="Hello Mike"
s.center(30,"=") #字符串居中对齐,输出宽度为30,不足的以“=”填充
#'==========Hello Mike=========='
s.ljust(20,"*") #字符串居左对齐,输出宽度为20,不足的以“*”填充
#'Hello Mike**********'
s.rjust(20,"*") #字符串居右对齐,输出宽度为20,不足的以“*”填充
#'**********Hello Mike'
s.zfill(20) #输出宽度为20,在字符串左侧以字符“0”填充
#'0000000000Hello Mike'