新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python字串查找要如何才能提高使用的速度
Python字串查找是一個十分有用的語句,我們在使用的時候有些小問題需要我們注意。其實這些問題都能在源代碼中找到相關的解決方案。下面我們就看看如何進行相關的學習。

10年積累的網(wǎng)站建設、網(wǎng)站制作經(jīng)驗,可以快速應對客戶對網(wǎng)站的新想法和需求。提供各種問題對應的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡服務。我雖然不認識你,你也不認識我。但先制作網(wǎng)站后付款的網(wǎng)站建設流程,更有秦淮免費網(wǎng)站建設讓你可以放心的選擇與我們合作。
如果讓你寫一個有關Python字串查找的程序檢查字符串s2中是不是包含有s1。也許你會很直觀的寫下下面的代碼:
- #determine whether s1 is a substring of s2
- def isSubstring1(s1,s2):
- tag = False
- lenlen1 = len(s1)
- lenlen2 = len(s2)
- for i in range(0,len2):
- if s2[i] == s1[0]:
- for j in range(0,len1):
- if s2[i]==s1[j]:
- tag = True
- return tag
可是這是Python,我們可以利用字符串自帶的find()方法,于是可以這樣:
- def isSubstring2(s1,s2):
- tag = False
- if s2.find(s1) != -1:
- tag = True
- return tag
悲情的事就在于此,原來Python中的關鍵字"in”不僅可以用于列表、元祖等數(shù)據(jù)類型,還可以用于字符串。所以,這里只需要直接一行代碼搞定:
- def isSubstring3(s1,s2):
- return s1 in s2后知后覺了,慚愧;-)
類似的,假設要在字符串中,查找多個子串是否存在,并打印出這些串和***出現(xiàn)的位置:
- def findSubstrings(substrings,destString):
- res = map(lambda x:str([destString.index(x),x]),filter
(lambda x:x in destString,substrings))- if res:
- return ', '.join(list(res)) ;-) very cool~UPDATE:
如果你不習慣***面這種看起來很復雜的語法也沒關系,可以使用列表解析,更加簡潔:
- def findSubstrings(substrings,destString): return ', '.join
([str([destString.index(x),x]) for x in substrings if x in destString])
以上就是對Python字串查找的相關介紹。
文章名稱:Python字串查找要如何才能提高使用的速度
網(wǎng)站路徑:http://m.5511xx.com/article/dhhjeed.html


咨詢
建站咨詢
