Sorry, today I wrote a python program for searching substrings...
If you want to write a program to check whether the string S2 contains S1. You may write the following code intuitively:
#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
However, this is Python. We can use the find () method that comes with the string, so we can do this:
def isSubstring2(s1,s2):
tag = False
if s2.find(s1) != -1:
tag = True
return tag
This is the sad thing. The original keyword "in" in python can be used not only for data types such as list and ancestor, but also for strings. Therefore, only one line of code is required:
def isSubstring3(s1,s2):
return s1 in s2
I am sorry for this ;-)
Similarly, suppose you want to search for the existence of multiple substrings in a string and print out the strings and their first appearance positions:
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: if you are not used to the last complex syntax, you can use list parsing to make it simpler:
def findSubstrings(substrings,destString):
return ', '.join([str([destString.index(x),x]) for x in substrings if x in destString])