Python字串查找要如何才能提高使用的速度
Python字串查找是一個十分有用的語句,我們在使用的時候有些小問題需要我們注意。其實這些問題都能在源代碼中找到相關(guān)的解決方案。下面我們就看看如何進行相關(guān)的學習。
如果讓你寫一個有關(guān)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中的關(guān)鍵字"in”不僅可以用于列表、元祖等數(shù)據(jù)類型,還可以用于字符串。所以,這里只需要直接一行代碼搞定:
- def isSubstring3(s1,s2):
- return s1 in s2后知后覺了,慚愧;-)
類似的,假設(shè)要在字符串中,查找多個子串是否存在,并打印出這些串和***出現(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:
如果你不習慣***面這種看起來很復雜的語法也沒關(guān)系,可以使用列表解析,更加簡潔:
- def findSubstrings(substrings,destString): return ', '.join
([str([destString.index(x),x]) for x in substrings if x in destString])
以上就是對Python字串查找的相關(guān)介紹。
【編輯推薦】