1、字符串 api
字符串是一個有序的字符集合,用於存儲和表示基本的文本信息,單引號、雙引號和三引號包含的內容稱之爲字符串。ide
字符串的特性:函數
一、按照從左到右的順序定義字符集合,下標從0開順序訪問,有序spa
二、能夠像列表那樣進行切片操做code
三、字符串不可變,不能像列表那樣進行修改其中的某個元素。orm
字符串的操做方法有不少,下面介紹一下比較經常使用的操做。對象
2、經常使用操做blog
一、capitalize()索引
capitalize() 函數是將字符串的首字母變成大寫,其他變成小寫。ip
s_tr = 'mY naMe is LiLei' print(s_tr.capitalize()) 結果: My name is lilei
二、lower()
lower()函數是將字符串中的大寫字符所有變爲小寫。
s_tr = 'mY naMe is LiLei' print(s_tr.lower()) 結果:my name is lilei
三、upper()
upper()函數是將字符串中的小寫字符所有變爲大寫。
s_tr = 'mY naMe is LiLei' print(s_tr.upper()) 結果:MY NAME IS LILEI
四、strip()
strip() 函數之後常常用到,做用是將字符串先後的空格去掉。
此外還有lstrip() 和 rstrip() 函數,lstrip()函數是將字符串左側的空格去除,rstrip()函數是將字符串右側的空格去除。
五、split()
split()函數是將字符串按照某個指定的字符,或者符號將字符串分割,並將分割的元素放入列表中,最終返回的是一個列表。
用法 split(分隔符,最大分割次數),若是不寫分隔符和最大分割次數,默認分隔符爲空格,並所有將字符串進行分割。
s_tr = 'my name is LiLei' print(s_tr.split()) 結果:['my', 'name', 'is', 'LiLei'] s_tr = 'my name is LiLei' print(s_tr.split(" ",maxsplit=2)) # 以空格爲分割符,最大分割數爲2,默認從左側開始計數 結果:['my', 'name', 'is LiLei']
還有rsplit()函數,是從字符串右側開始進行分割,用法和split()函數相似。
六、count()
count(self,sub,start=None,end=None)函數是統計指定的字符在字符串中的數量,能夠經過start 和 end來控制字符串的查詢範圍。
s_tr = 'my name is LiLei' print(s_tr.count("m")) s_tr = 'my name is LiLei' print(s_tr.count("m", 0, 5)) 結果: 2 1
七、startswith()和endswith
startswith(self,sub,start=None,end=None) 和 endswith(self,sub,start,end) ,這兩個函數分別表示以什麼字符開頭或結尾,返回True和False。
s_tr = 'my name is LiLei' print(s_tr.startswith("m")) s_tr = 'my name is LiLei' print(s_tr.endswith("i")) 結果: True True
八、center()、ljust(), rjust()
center(self,width,fillchar) 函數是將字符串兩端用特定的符號進行填充,字符串居中顯示,width寬度指的是顯示的總寬度,若是設定值小於字符串長度,將起不到填充效果。
s_tr = 'my name is LiLei' print(s_tr.center(30, "-")) s_tr = 'my name is LiLei' print(s_tr.center(10, "-")) # 設定總寬度小於字符串寬度 結果: -------my name is LiLei------- my name is LiLei
ljust(self,width,fillchar)是在字符串右側填充特殊字符,rjust(self,width,fillchar)是在字符串左側填充特殊字符。
st = "My name is lilei" print(st.ljust(20, "-")) print(st.rjust(20, "-")) 結果: My name is lilei---- ----My name is lilei
九、join()
join(self,iterable)函數是將列表、元組等而可迭代的對象用特定字符拼接起來,造成新的字符串。
List = ["my", "name", "is", "lilei"] s_tr = '-' print(s_tr.join(List)) 結果:my-name-is-lilei
十、find()
find(self,sub,start,end) 是找出指定的字符元素在字符串中的位置,返回的是第一個結果的索引值
s_tr = "my name is lilei" print(s_tr.find("m")) 結果:0
十一、replace()
replace(self,old,new,count) 函數是對字符串中的某個元素用新的字符進行替換,count不指定默認將字符串中的舊字符所有替換,指定的話,只對舊字符進行指定次數的替換。
s_tr = "my name is lilei" print(s_tr.replace("m", "M")) s_tr = "my name is lilei" print(s_tr.replace("m", "M", 1)) 結果: My naMe is lilei My name is lilei
十二、format()
format(self,*args,**kwargs) 是一種格式化字符串的函數。基本語法是經過{}和:來替代以前的%。format函數能夠接受不限個數參數,位置也能夠不按順序。
st = "My name is {0}, age is {1}" print(st.format("lilei", 18)) st = "My name is {name}, age is {age}" print(st.format(age=18, name='lilei')) 結果: My name is lilei, age is 18 My name is lilei, age is 18
1三、zfill()
zill(self,width)函數是在字符串左側填充0.
st = "My name is lilei" print(st.zfill(25)) 結果:000000000My name is lilei