python字串常用方法

2021-10-07 19:35:53 字數 1650 閱讀 9850

print

(str1.title())

# 首字母大寫

result: dlrowollehnohtypolleh

print

(str1.upper())

# 將所有字母大寫

result: hellopythonhelloworld

print

(str1.title())

# 將首字母大寫

result: hellopythonhelloworld

print

(str1.find(

'h',18,

20))# 查詢某個值 可以寫範圍 找不到返回-1

result:

-1

print

(str1.rfind(

'l')

)# 從左邊開始查詢 返回是從右開始的下標

result:

19

print

(str1.index(

'w')

)# 返回下標

result:

16

print

(str1.replace(

'l',

'2',5)

)# 替換 5為替換次數

result: he22opythonhe22owor2d

print

(str1.split(

'l',1)

)# 分割 1為分割的次數

result:

['he'

,'lopythonhelloworld'

]

print

(str1.rsplit(

'l',1)

)# 分割 和split是一樣的,只不過是從右邊開始分割

result:

['hellopythonhellowor'

,'d'

]

print

(str1.strip())

# 去除首尾空格

result: hellopythonhelloworld

print

(str1[2:

7])# 下標從2:7的資料

result: llopy

print

(str1[1:

:7])

# ph,eood 步長值就是中間隔 (count-1)個字母再擷取

result: eho

print

(str1[1:

:7])

# ph,eood 步長值就是中間隔 (count-1)個字母再擷取

result: eho

print

(str1[::

-1])

# 字串逆轉

result: dlrowollehnohtypolleh

python 字串常用方法

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

Python字串常用方法

count 獲取字串中某個字元的數量。str python count str.count o 2strip 刪除字串首位的空格,以及換行。str1 hello python str2 hello python str3 hello python str1.strip str2.strip str3...

python字串常用方法

string.title python title 方法返回 標題化 的字串,就是說所有單詞都是以大寫開始,其餘字母均為小寫 見 istitle string.upper python upper 方法將字串中的小寫字母轉為大寫字母。string.lower 將字串的大寫字母轉為小寫字母 strin...