Python語言字串處理和特殊函式

2021-08-20 08:28:42 字數 2449 閱讀 4685

字串:用引號括起來的字元集合。引號可以是單引號,雙引號甚至是三引號。

str1='hello'       #定義字串

str2="hello"

str3='''hello'''

print 'hello "man"'  #輸出hello "man"
訪問字串裡的值

字串格式化

print "my name is %s and age is %d"% ('zw' 18)
字串各種函式

astr = 'hello world itcast and itcastcpp'
find函式:檢測 it中是否包含在astr中,存在則讀出,不存在則返回-1.

index函式和fing一樣,區別在於當查詢的內容不在字串中時,報告異常。

count函式:統計子串在字串中出現的次數。

astr.count(it,0,len(astr))   #返回值為2
decode函式:以指定的編碼格式解碼   encode函式:以指定的編碼格式編碼。

replace函式:將astr中的str1替換成str2,如果count指定,則替換次數不超過count次。

astr.replace( str1, str2, astr.count(str1))
split函式:以str為分隔符切片astr。

astr.split(str=" ",2)  #以空格分割為列表,然後使用  2為分割次數
將字串切割,排序的例子

過濾字串的空格:過濾左邊的空格用astr.lstrip();     過濾右邊的空格用astr.rstrip();

partition函式:分割函式

函式高階

定義乙個函式

新建乙個text.py,寫入下方**:

def printname(str):

'輸出你的名字' #函式注釋

print str

return

import text   #將函式匯入text
text.printname('cpp')

#返回值cpp

help(test.printname)

#返回 輸出你的名字

引數引數型別:1.必備引數 2.命名引數 3.預設引數 4.不定場引數。

1.必備引數 :呼叫的順序不能變,數量不能變,否則報錯。

2.命名引數:呼叫方可以用引數的命名來確定傳入的引數值。

3.預設引數:定義的值如果沒有被傳入,則認為是預設值。

例1.

例2.匿名函式lambda:

Python 字串處理

python endswith 方法用於判斷字串是否以指定字尾結尾,如果以指定字尾結尾返回 true 否則返回 false 可選引數 start 與 end 為檢索字串的開始與結束位置。語法 endswith 方法語法 str.endswith suffix start end 引數 返回值 如果字...

Python字串處理

去空格及特殊符號 s.strip lstrip rstrip 複製字串 strcpy sstr1,sstr2 sstr1 strcpy sstr2 sstr1 sstr1 strcpy2 print sstr2連線字串 strcat sstr1,sstr2 sstr1 strcat sstr1 ss...

Python字串處理

python字串處理 part i 常見處理函式 string.find sub,start 0,end len string 檢測sub是否包含在string中,如果是返回 第乙個sub 開始的索引值,否則返回 1.string.index sub,start 0,end len string 跟...