python 字串中的內建函數(附程式碼片段) 總結一
1, find ( )檢測字串
用法格式:str1.find(str2) #在str1中 檢索字串str2是否存在,存在,返回str2的初地址,不存在,返回-1. str1.find(str2,x)#x是表示下標的變數,意為:從下標為x的位置開始檢索str2是否存在於str1中. str.find(str2,x,y)#y表示下標整型變數, 意為:從下標x開始,檢測到下標y結束
>>> str1 = "hello,world,nihao,shijie">>> str2 = "ll">>> str1.find(str2)2>>> str1.find(str2,1)2>>> str1.find(str2,2)2>>> str1.find(str2,3)-1>>> str1.find(str2,1,6)2>>> str1.find(str2,1,4)2>>> str1.find(str2,1,3)-1
2,rfind( )反向(從右至左)檢測字串 str2最後出現的 下標
str1.rfind(str2)#從 str1中從右至左檢測str2是否存在str1.rfind(str2,x,y)#【x,y)定位檢索的位置,之後正常反向檢索,輸出字串首字母下標。
>>> str1.rfind(str2)2>>> str1.rfind(str2,0)2>>> str1.rfind(str2,2)2>>> str1.rfind(str2,2,3)-1>>> str1.rfind(str2,2,5)2
3,count()方法文法:
str.count(str1)#計數 str中,子串”str1“出現的次數
str.count(str1,x)#計數 str中從下標x開始,子串”str1“出現的次數
str.count(str1,x,y)#計數 str中從下標x開始,子串”str1“出現的次數
>>> str = "hello,world,nihao,shijie">>> count(",")Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'count' is not defined>>> str.count(",")3>>> str.count("l")3>>> str.count("i")3>>> str = "hellohellohello">>> str.count("llo")3>>> str = "hellohhhehehhe">>> str.count("he")4
4,split()方法文法
str.split( )#預設切片條件為:所有的Null 字元,包括空格、換行(\n)、定位字元(\t)等
**str.split(str1,num)#切片條件為:檢索到str1,切片次數為num
*利用re模組進行切片(同時包含多個分隔字元的檢索)代碼如下:import rea=str#待檢測字串x=re.split( 此處為多個輸入的分隔字元 ,a)print(x)
>>> str = "he l l o,wo rld,hi,shijie\t,nihao,\nhi hihi">>> str.split()['he', 'l', 'l', 'o,wo', 'rld,hi,shijie', ',nihao,', 'hi', 'hihi']>>> str 'he l l o,wo rld,hi,shijie\t,nihao,\nhi hihi'>>> str.split(",",2)['he l l o', 'wo rld', 'hi,shijie\t,nihao,\nhi hihi']>>> str.split(",",3)['he l l o', 'wo rld', 'hi', 'shijie\t,nihao,\nhi hihi']>>> str.split("o",2)['he l l ', ',w', ' rld,hi,shijie\t,nihao,\nhi hihi']>>> import re >>> a = "zhang,shijie ,ni,hao">>> x = re.split(', h j ',a)>>> print x['zhang,shijie ,ni,hao']
5,max()方法文法 max(str)#輸出字串中的最大字元
6,min()方法文法 min(str)
>>> str = "abcdshjshf">>> max(str)'s'>>> min(str)'a'>>> str = "12345676789">>> max(str)'9'>>> min(str)'1'
7,lower()方法文法:
str.lower()#直接將字串str中的所有大寫字母轉換成小寫字母
>>> str = "ZGAHHHhihhoioai">>> str.lower()'zgahhhhihhoioai'
8,replace()方法文法:
str.replace(old,new)#直接將老字串替換為新的字串
str.replace(old,new[,max])#指定參數max,以為替換次數不超過max;
>>> str = "this is in china">>> str.replace("is",'was',1)'thwas is in china'>>> str.replace("is",'was',2)'thwas was in china'>>>
9,index()方法文法:
str.index(str1)用法同find(),只是如果被檢測的字串中不含想要尋找的內容的話,會報一個異常
>>> str.index("is")2>>> str.index("wax")Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: substring not found
10,rindex()類似於index(),方向為從右至左
11,lstrip()方法文法:rstrip()同用法
str.lstrip()#截掉字串左邊的空格(有多少,截掉多少)
>>> str = " this is China">>> str.lstrip()'this is China'>>> str = "zhang ">>> str.rstrip()'zhang'
暫時總結這麼多。。。。。待續