Shame, today wrote a search substring of the Python program was BS ...
If you are asked to write a program to check whether the string S2 contains S1. Perhaps you will be very intuitive to write down the following code:
Copy Code code as follows:
#determine whether S1 is a substring of S2
def isSubstring1 (S1,S2):
Tag = False
Len1 = Len (S1)
Len2 = 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
But this is Python, we can use the string from the Find () method, so you can:
Copy Code code as follows:
def isSubstring2 (S1,S2):
Tag = False
If S2.find (S1)!=-1:
Tag = True
return tag
This is the sad thing, the original python keyword "in" can be used not only for lists, Ganso and other data types, but also for strings. So, here's just one line of code to fix:
Copy Code code as follows:
def isSubstring3 (S1,S2):
return S1 in S2
After knowing, ashamed;--)
Similarly, suppose you want to find the existence of multiple substrings in a string, and print out these strings and where they first appear:
Copy Code code as follows:
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: It doesn't matter if you're not used to this seemingly complicated syntax at the end, you can use list parsing to be more concise:
Copy Code code as follows:
def findsubstrings (substrings,deststring):
Return ', '. Join ([Str ([Deststring.index (x), X]) for x into substrings if x in deststring])