python中字串常用方法總結

2021-08-21 20:54:07 字數 2554 閱讀 6454

# 字串的常用操作

# 1. 大小寫轉換

str1 = "hellopythonhelloworld"

str2 = "hello python 999, hello world"

str3 = "hellopython,helloworld"

print(str2.title()) # 返回每個單詞首字母大寫,其他字母小寫的字串

print(str2.capitalize()) # 返回首字母大寫,其他字母全部小寫的新字串

print(str1.upper()) # 將字串中的每個字母大寫

print(str3.lower()) # 將左右字母變小寫

print(str3.swapcase()) # 將字串中的字母大寫轉小寫,小寫轉大寫

# 2. .is*** 的判斷

str1 = "hellopythonhelloworld"

str2 = "hello python 999, hello world"

str3 = "23346546756535"

print(str1.isalpha()) # 判斷字串中是否全是字母(加乙個標點符號會是false)

print(str2.isdecimal()) # 檢測是否都是數字

print(str1.isdigit()) #檢測字串是否都是數字 (false)

print(str2.isdigit()) #(false)

print(str3.isdigit()) #(true)

print(str2.isnumeric()) # 檢測是否都是數字 (這三種方法有區別,如需要,請詳查)

str4 = "hellopythonhelloworld666"

print(str4.isalnum()) # 判斷字串是否是字母或數字 ,全是字母(true) 全是數字(true) 字母和數字(true)

str5 = " "

print(str5.isspace()) # 判斷是否都是空格

# 3. 查詢

print(str4.find("h", 4, 9)) # 查詢指定子串的位置,find從左到右查詢, 下標(0), (若找不到則返回-1)

print(str4.rfind("h")) #rfind從右到左查詢,下標 (11) ,也就是從最右邊開始找到的子串,但是下標從左邊開始,不能混淆

print(str4.index("e")) # 找到則返回下標,找不到會報錯

# 4. 替換

print(str4.replace("hello", "hello", 2)) # str.replace(old, new[, count]) count 是替換次數

# 5. 字串的分割, 並生成乙個列表

str5 = "星期一 | 星期二 | 星期三 | 星期四 | 星期五"

print(str5.split("|", 3)) # 可以指定分割次數

print(str5.rsplit("|")) #rsplit()和split()是一樣的,只不過是從右邊向左邊搜尋。

# splitlines()用來專門用來分割換行符。雖然它有點像split('\n')或split('\r\n')

# splitlines()中可以指定各種換行符,常見的是\n、\r、\r\n。如果指定keepends為true,則保留所有的換行符。

str6 = "abc\n\ndef \rgh\nijk\r\n"

print(str6.splitlines()) # 結果:['abc', '', 'def ', 'gh', 'ijk']

print(str6.splitlines(keepends=true)) # 結果: ['abc\n', '\n', 'def \r', 'gh\n', 'ijk\r\n']

# 6. 去掉空白字元

str7 = " abcdefghijkl mn "

print(str7.lstrip()) # 去掉左邊(開始)的空白字元

print(str7.rstrip()) # 去掉右邊(末尾)的空白字元

print(str7.strip()) # 去掉兩邊的空白字元

# 7. 字串的切片 字串[開始索引 : 結束索引 :步長值]

# 指定的區間屬於左閉右開[開始索引,結束索引)

str8 = "hello python, hello world"

print(str8[6 : 12])

print(str8[6 : : 3]) #ph,eood 步長值就是中間隔 (count-1)個字母再擷取

print(str8[: : -1]) # 字串的逆序

python中字串常用方法

str python string function 生成字串變數str python string function 字串長度獲取 len str 例 print s length d str,len str 一 字母處理 全部大寫 str.upper 全部小寫 str.lower 大小寫互換 s...

Python中字串常用的方法

python中字串常用的方法 information this is shanghai city,information1 it s very bustling aaa i come from and myhometown is print information.center 50,長度為50,並...

python 字串常用方法

python 字串的常用方法 1.len str 字串的長度 2.startswith str 檢視字串是否以str子串開頭,是返回true,否則返回false 3.index str 查詢字串中第一次出現的子串str的下標索引,如果沒找到則報錯 4.find str 查詢從第0個字元開始查詢第一次...