python字符串的index和find的區(qū)別詳解
1.find函數(shù)
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函數(shù)
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 函數(shù)
Python join() 方法用于將序列中的元素以指定的字符連接生成一個新的字符串。
lis=['a','b','c','d','e'] string='abcde' tup=('a','b','c','d','e') print(''.join(lis)) print(' '.join(string)) print('$'.join(tup)) #運行結果 abcde a b c d e a$b$c$d$e
注意序列里的元素必須是字符串,不能是數(shù)字
4.split函數(shù)
split() 通過指定分隔符對字符串進行切片,如果第二個參數(shù) 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', 'is', 'an interesting story!'] ['thi', ' i', ' an intere', 'ting ', 'tory!'] ['this is an interesting story!']
5.strip函數(shù)
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的區(qū)別詳解的文章就介紹到這了,更多相關python字符串的index和find的區(qū)別內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
opencv python 圖片讀取與顯示圖片窗口未響應問題的解決
這篇文章主要介紹了opencv python 圖片讀取與顯示圖片窗口未響應問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04Python Pandas學習之基本數(shù)據(jù)操作詳解
本文將通過讀取一個股票數(shù)據(jù),來進行Pandas的一些基本數(shù)據(jù)操作的語法介紹。文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2022-02-02