Python 字串常用函式

2021-10-05 02:34:11 字數 2964 閱讀 7226

函式

描述(返回值)

str.capitalize() 

將字串的第乙個字元大寫

str.title()

返回標題化的字串,即每個單詞的首字母都大寫

str.upper()

全大寫str.lower()

全小寫len(str)

返回字串的長度。用法與其他不同。

str.count(substring[,start[,end]])    

統計字串裡某個子串出現的次數。三個引數:搜尋的子串、搜尋的開始位置、結束位置。後2個可選,預設時預設為0、-1

可選引數為在字串搜尋的開始與結束位置

str.center(width[,fillchar])

返回乙個指定寬度 width 居中的字串,fillchar 為填充的字元(只能是乙個字元,不能是字串,下2個同),預設為空格。

ljust(width[, fillchar])

返回乙個原字串左對齊,並使用 fillchar 填充至長度 width 的新字串,fillchar 預設為空格。

rjust(width[, fillchar])

返回乙個原字串右對齊,並使用fillchar(預設空格)填充至長度 width 的新字串

lstrip([substring])

刪掉字串開頭的子串substring。開頭的substring才會被刪除。引數預設時預設為空格。

rstrip([substring])

刪掉字串開頭的子串substring。開頭的substring才會被刪除。引數預設時預設為空格。

strip([substring])

lstrip()+rstrip()

str.encode("utf-8")

以指定字符集編碼,返回編碼後的字串

str.decode("utf-8")

以指定字符集解碼,返回解碼後的字串。需要在之前使用encode()編碼,才能使用decode()

str.startswith(substring[,satrt[,end]])    

檢查字串是否是以指定子字串 substr 開頭,返回值是bool型別。三個引數:搜尋的子串、搜尋的開始位置、結束位置。後2個可選,預設時預設為0、-1

endswith(substring[, start[, end]])

判斷字串是否以指定子串結尾

str.find(substring[, start[, end]])

在str中查詢指定子串,找到就返回子串的位置(索引),找不到就返回-1

str.rfind(substring[, start[, end]])

同find(),只不過是從右向左找

str.index(substring[, start[, end]])

同find(),只不過找不到時是報錯(error)

str.rfind(substring[, start[, end]])

從右向左找

str.replace(oldsub, newsub [, maxcount])

替換子串,count指5定最大替換次。比如max=5,則替換5次,str中不足5個匹配時,有多少個就替換多少個。

str.expandtabs(1)

把字串中的\t替換為指定個數的空格,\t的預設空格數是 8 ,引數指定空格數,預設時預設為8(不替換)

str.split([substring[, count]])

將字串切割為字串列表,返回字串列表。substring指定分隔符(預設為空格,乙個或多個空格都行),count指定切割次數(預設為-1,全部切完)。切一刀會得到2個子串(後面作為乙個整體)。

連線符.join(seq)

以指定字串作為連線符,將 seq 中所有的元素連線為乙個字串,並返回這個字串。seq必須為字串序列,否則報錯。

str = "

hellohello world

"print(str.lstrip("

hello

")) #

開頭的2個hello都會被刪除

str="

hello hello

"print(str.lstrip("

hello

")) #

只會刪除第乙個hello

str="

!hello hello

"print(str.lstrip("

hello

")) #

hello不是字串開頭,所以不會刪除

"""l/rstrip(),先判斷substring是不是字串的開頭/結尾,是才刪除(多個連著時,會刪除多個)

strip()相當於lstrip()+rstrip(),只刪除開頭、結尾處的,並不是全部刪除。

"""

str = "

hello world

"print(str.split("

o")) #

['hell', ' w', 'rld']

print(str.split("

o",1)) #

['hell', ' world'] 一刀2段,後面作為乙個整體

seq=["

hello

","world

","ok"]

print("

".join(seq)) #

hello world ok 以空格連線

print("

**".join(seq)) #

hello**world**ok 以**連線

eval("

print(1)

") #

1exec("

print(2)

") #

2

eval(str)、exec(str)都是執行字串中的python**,只不過exec()功能更加強大。

PYTHON字串常用函式

1.find and rfind 從左開始找 title find le 存在返回索引值,不存在 1 從右開始找 title find le 存在返回索引值,不存在 1 2.join 列表轉成字串 join list 3.split 字串轉成列表 ss,aa,cc split ss aa cc 4....

Python字串常用函式

capitalize 把字串的第乙個字元改為大寫 casefold 把整個字串的所有字元改為小寫 center width 將字串居中,並使用空格填充至長度width的新字串 count sub start end 返回sub在字串裡邊出現的次數,start和end引數表示範圍,可選。encode ...

Python 字串常用函式

capitalize 把第乙個字母轉為大寫 str1 aaaaa str1.capitalize aaaaaa casefold 把所有字元轉為小寫 str2 bbbbaa str2.capitalize bbbbaa count sub,start,end 返回sub在原字串出現的次數,start...