字符串搜索相關搜索指定字符串,沒有返回-1:str.find('t')指定起始位置搜索:str.find('t',start)指定起始及結束位置搜索:str.find('t',start,end)從右邊開始查找:str.rfind('t')搜索到多少個指定字符串:str.count('t')上面所有方法都可用index代替,不同的是使用index查找不到會拋異常,而find返回-1print '%s find nono=%d' % (str,str.find('nono'))print '%s find t=%d' % (str,str.find('t'))print '%s find t from %d=%d' % (str,1,str.find('t',1))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))print '%s rfind t=%d' % (str,str.rfind('t'))print '%s count t=%d' % (str,str.count('t'))
字符串替換相關替換old為new:str.replace('old','new')替換指定次數的old為new:str.replace('old','new',maxReplaceTimes)print '%s replace t to *=%s' % (str,str.replace('t', '*'))print '%s replace t to *=%s' % (str,str.replace('t', '*',1))
將字符串前n個字符替換為指定的字符
#strnset(sStr1,ch,n)sStr1 = '12345'ch = 'r'n = 3sStr1 = n * ch + sStr1[3:]print sStr1
復制指定長度的字符
#strncpy(sStr1,sStr2,n)sStr1 = ''sStr2 = '12345'n = 3sStr1 = sStr2[0:n]print sStr1字符串去空格及去指定字符去兩邊空格:str.str 按指定字符分割字符串為數組: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('-')) 字符串判斷相關是否以start開頭:str.startswith('start')是否以end結尾:str.endswith('end')是否全為字母或數字:str.isalnum()是否全字母:str.isalpha()是否全數字:str.isdigit()是否全小寫:str.islower()是否全大寫:str.isupper()str='python String function'print '%s startwith t=%s' % (str,str.startswith('t'))print '%s endwith d=%s' % (str,str.endswith('d'))print '%s isalnum=%s' % (str,str.isalnum())str='pythonStringfunction'print '%s isalnum=%s' % (str,str.isalnum())print '%s isalpha=%s' % (str,str.isalpha())print '%s isupper=%s' % (str,str.isupper())print '%s islower=%s' % (str,str.islower())print '%s isdigit=%s' % (str,str.isdigit())str='3423' print '%s isdigit=%s' % (str,str.isdigit()) 數字變為字符串 str() 怎么把字符串轉換成數字? int('1234') 連接字符串sStr1 = 'strcat'sStr2 = 'append'sStr1 += sStr2print sStr1復制字符串#strcpy(sStr1,sStr2)sStr1 = 'strcpy'sStr2 = sStr1sStr1 = 'strcpy2'print sStr2比較字符串#strcmp(sStr1,sStr2)sStr1 = 'strchr'sStr2 = 'strch'print cmp(sStr1,sStr2) #注意cmp函數的輸出結果和C語言的strcmp是一樣的。還可以用 “aaa”==“bbb” 來比較字符串。 字符串的分割和組合:S.split([sep, [maxsplit]]) #以sep為分隔符,把S分成一個list。maxsplit表示分割的次數。默認的分割符為空白字符 S.rsplit([sep, [maxsplit]]) S.splitlines([keepends]) #把S按照行分割符分為一個list,keepends是一個bool值,如果為真每行后而會保留行分割符。 S.join(seq) #把seq代表的序列──字符串序列,用S連接起來字符串的mapping,這一功能包含兩個函數:String.maketrans(from, to) #返回一個256個字符組成的翻譯表,其中from中的字符被一一對應地轉換成to,所以from和to必須是等長的。 S.translate(table[,deletechars]) # 使用上面的函數產后的翻譯表,把S進行翻譯,并把deletechars中有的字符刪掉。需要注意的是,如果S為unicode字符串,那么就不支持 deletechars參數,可以使用把某個字符翻譯為None的方式實現相同的功能。此外還可以使用codecs模塊的功能來創建更加功能強大的翻譯 表。 翻轉字符串 資料來源: http://www.jb51.net/article/33631.htm http://www.cnblogs.com/emanlee/p/3616755.html http://www.jb51.net/article/47956.htm
新聞熱點
疑難解答