字串的常用操作方法

2022-07-22 13:33:16 字數 1110 閱讀 2417

join  => 字串拼接  =>>>  語法: 「拼接符」  .join(拼接的資料)  :  將字串、元組、列表中的元素以指定的字元(拼接符)連線生成乙個新的字串

列:>> a=['1','2','3','4','5']

>> '  '.join(a)

1 2 3 4 5

>>'-'.jion(a)

1-2-3-4-5

>>'.'.join(a)

1.2.3.4.5

find => 找到元素的位置  =>>> 語法  : 

str.find(str,beg=0,end=len(string))     1.

str -- 指定檢索的字串    2.beg -- 開始索引,3.預設為0。end -- 結束索引,預設為字串的長度 

***  如果包含子字串返回開始的索引值,否則返回-1

列:>>>info= 'abca'

>>> printinfo.find('a')  # 從下標0開始,查詢在字串裡第乙個出現的子串,返回結果:00

>>> printinfo.find('a',1)# 從下標1開始,查詢在字串裡第乙個出現的子串:返回結果3

3>>>

print

info

.find('

3')# 查詢不到返回-1-1

>>>

count => 用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。  =>>>  語法 ; 

str.count(sub,start=0,end=len(string))

1.sub -- 搜尋的子字串start -- 字串開始搜尋的位置。2.預設為第乙個字元,第乙個字元索引值為0。3.end -- 字串中結束搜尋的位置。字元中第乙個字元的索引為 0。預設為字串的最後乙個位置。

列:>>str= "this is string example....wow!!!";

>>sub= "wow"

;>>print(str.count(sub))

>>1

replace  =>> 把字串中的 old(舊字串) 替換成 new(新字串),如果指定第三個引數max,則替換不超過 max 次  =>>>> 

python字串常用操作方法

1.去除空格 str.strip 刪除字串兩邊的指定字元,括號的寫入指定字元,預設為空格 a hello b a.strip print b hellostr.lstrip 刪除字串左邊的指定字元,括號的寫入指定字元,預設為空格 a hello b a.lstrip print b hello 右邊...

python字串的常用操作方法

captilze 首字母大寫 swapcase 大小寫反轉 upper 全部大寫 lower 全部小寫 find 通過元素找索引,找到第乙個就返回,可以切片,找不到返回 1.index 通過元素找索引,找到第乙個就返回,可以切片,找不到報錯.replace old,new,count 替換。cent...

字串操作方法

indexof 返回查詢某乙個字串第一次出現的下標 定義字串 string.indexof 要查詢的字串 從哪一下標開始 返回第一次出現的下標 slice 擷取字串兩個引數第乙個是開始的下標,第二個是結束的下標,如果第乙個引數是負數就是倒數下標。str.slice 開始的位置,結束的位置 split...