Python字串常見操作

2021-09-01 06:11:59 字數 1975 閱讀 4783

如有字串mystr = 'hello world hello everyone',以下是常見的操作

<1>find與index

檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則find返回-1,index將報錯。

返回 str 在 mystr裡面出現的次數,可以指定查詢範圍。

把 mystr 中的 str1 替換成 str2,如果 count 指定,則替換不超過 count 次。

mystr.replace(str1,str2,count)

此 操作返回乙個新的字串,原字串mystr不變。

以 str 為分隔符切片 mystr,如果 maxsplit有指定值,則僅分隔 maxsplit 次,將返回maxsplit+1個子串組成的列表。mystr.split(str=" ", 2)

把字串的第乙個字元大寫,同時會將其他的大寫字母變成小寫。返回改變後的新字串,原字串不變。此時mystr="hello world hello everyone"

把字串的每個單詞首字母大寫,同時改變其他字母適當的狀態,返回新字元

<7>startswith和endswith

這兩個方法分別檢查字串是否是以 str 開頭或結尾, 是則返回 true,否則返回 false

<8>lower和upper

分別將 mystr 中所有大寫字元變為小寫,將小寫字母變成大寫

<9>ljust,rjust和center

接收乙個引數width,返回乙個原字串分別左對齊,右對齊和居中,並用空格填充至width長度的新字串。此時將mystr重新賦值mystr="hello"

將str插入到mystr各個字元之間,例如",".join(mystr)

將mystr換成列表或元組

如果是字典呢

join就是將乙個字串插入到另乙個字串各字元之間或者是列表和元組各元素之間,並返回乙個新字串。字典只作用於keys或values,實際上還是列表。

<11>strip,lstrip和rstrip

strip去除字串左右兩邊的空白字元,lstrip和rstrip就是分別去除左邊或右邊的空白字元。返回新字串,原字串不變。

Python字串常見操作

先初始化乙個字串scstring scstring my name is shenchong shen shen find scstring my name is shenchong shen shen print scstring.find shen 輸出結果,第乙個shen的s的角標為11 11...

python中字串常見操作

mystr hello world,this is python 1 find 檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則返回 1 mystr.find str,start 0,end len mystr mystr hello world,this is python m...

python常見字串操作

str hello world print str.upper 把所有字元中的小寫字母轉換成大寫字母 print str.lower 把所有字元中的大寫字母轉換成小寫字母 print str.capitalize 把第乙個字母轉化為大寫字母,其餘小寫 print str.title 把每個單詞的第乙...