1. 程式人生 > 程式設計 >python字串的index和find的區別詳解

python字串的index和find的區別詳解

1.find函式

find() 方法檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,如果指定範圍內如果包含指定索引值,返回的是索引值在字串中的起始位置。如果不包含索引值,返回-1。

string='abcde'
x=string.find('a')
y=string.find('bc')
z=string.find('f')
print(x)
print(y)
print(z)
#執行結果
0
1
-1

2.index函式

index() 方法檢測字串中是否包含子字串 str ,如果指定 beg(開始) 和 end(結束) 範圍,則檢查是否包含在指定範圍內,該方法與 python find()方法一樣,只不過如果str不在 string中會報一個異常。

string='abcde'
x=string.index('a')
y=string.index('bc')
#z=string.index('f')
print(x)
print(y)
#print(z)
0
1
ValueError: substring not found

3.join 函式

Python join() 方法用於將序列中的元素以指定的字元連線生成一個新的字串。

lis=['a','b','c','d','e']
string='abcde'
tup=('a','e')
print(''.join(lis))
print(' '.join(string))
print('$'.join(tup))
#執行結果
abcde
a b c d e
a$b$c$d$e

注意序列裡的元素必須是字串,不能是數字

4.split函式

split() 通過指定分隔符對字串進行切片,如果第二個引數 num 有指定值,則分割為 num+1 個子字串。

str.split(str="",num=string.count(str))

string='this is an interesting story!'
a=string.split()
b=string.split(' ',2)
c=string.split('s')
d=string.split(',')
print(a)
print(b)
print(c)
print(d)
#執行結果
['this','is','an','interesting','story!']
['this','an interesting story!']
['thi',' i',' an intere','ting ','tory!']
['this is an interesting story!']

5.strip函式

Python strip() 方法用於移除字串頭尾指定的字元(預設為空格)或字元序列。

注意:該方法只能刪除開頭或是結尾的字元,不能刪除中間部分的字元。

string='**this is an ***interesting story!***'
a=string.strip('*')
b=string.lstrip('*')
c=string.rstrip('*')
print(string)
print(a)
print(b)
print(c)
#執行結果
**this is an ***interesting story!***
this is an ***interesting story!
this is an ***interesting story!***
**this is an ***interesting story!

lstrip和rstrip分別去掉左邊和右邊的指定字元。

到此這篇關於python字串的index和find的區別詳解的文章就介紹到這了,更多相關python字串的index和find的區別內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!