str='python String function'
生成字符串變量str='python String function'
字符串長(zhǎng)度獲取:len(str)
例:print '%s length=%d' % (str,len(str))
字母處理
全部大寫(xiě):str.upper()
全部小寫(xiě):str.lower()
大小寫(xiě)互換:str.swapcase()
首字母大寫(xiě),其余小寫(xiě):str.capitalize()
首字母大寫(xiě):str.title()
print '%s lower=%s' % (str,str.lower())
print '%s upper=%s' % (str,str.upper())
print '%s swapcase=%s' % (str,str.swapcase())
print '%s capitalize=%s' % (str,str.capitalize())
print '%s title=%s' % (str,str.title())
格式化相關(guān)
獲取固定長(zhǎng)度,右對(duì)齊,左邊不夠用空格補(bǔ)齊:str.ljust(width)
獲取固定長(zhǎng)度,左對(duì)齊,右邊不夠用空格補(bǔ)齊:str.ljust(width)
獲取固定長(zhǎng)度,中間對(duì)齊,兩邊不夠用空格補(bǔ)齊:str.ljust(width)
獲取固定長(zhǎng)度,右對(duì)齊,左邊不足用0補(bǔ)齊
print '%s ljust=%s' % (str,str.ljust(20))
print '%s rjust=%s' % (str,str.rjust(20))
print '%s center=%s' % (str,str.center(20))
print '%s zfill=%s' % (str,str.zfill(20))
字符串搜索相關(guān)
搜索指定字符串,沒(méi)有返回-1:str.find('t')
指定起始位置搜索:str.find('t',start)
指定起始及結(jié)束位置搜索:str.find('t',start,end)
從右邊開(kāi)始查找:str.rfind('t')
搜索到多少個(gè)指定字符串:str.count('t')
上面所有方法都可用index代替,不同的是使用index查找不到會(huì)拋異常,而find返回-1
print '%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'))
字符串替換相關(guān)
替換old為new:str.replace('old','new')
替換指定次數(shù)的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))
字符串去空格及去指定字符
去兩邊空格:str.strip()
去左空格:str.lstrip()
去右空格:str.rstrip()
去兩邊字符串:str.strip('d'),相應(yīng)的也有l(wèi)strip,rstrip
str=' python String function '
print '%s strip=%s' % (str,str.strip())
str='python String function'
print '%s strip=%s' % (str,str.strip('d'))
按指定字符分割字符串為數(shù)組:str.split(' ')
默認(rèn)按空格分隔
str='a b c de'
print '%s strip=%s' % (str,str.split())
str='a-b-c-de'
print '%s strip=%s' % (str,str.split('-'))
字符串判斷相關(guān)
是否以start開(kāi)頭:str.startswith('start')
是否以end結(jié)尾:str.endswith('end')
是否全為字母或數(shù)字:str.isalnum()
新聞熱點(diǎn)
疑難解答
圖片精選