Tips for finding substrings in Python strings

  • 2020-05-07 19:58:29
  • OfStack

Shame on you, today I wrote a find substring Python program BS...

If you write a program to check if the string s2 contains s1. You might 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

But this is Python, and we can use the find() method that comes with strings, so we can do this:


def isSubstring2(s1,s2):
    tag = False
    if s2.find(s1) != -1:
        tag = True
    return tag

The sad thing is that the original keyword "in "in Python can be used not only for data types such as lists and primitives, but also for strings. So, it only takes 1 line of direct code:

def isSubstring3(s1,s2):
    return s1 in s2

After knowing, after feeling, ashamed; -)

Similarly, suppose you want to look for the existence of multiple substrings in a string, and print out the strings and the locations where they first appear:


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're not used to this very complicated looking syntax at the end, you can use list parsing to make it more concise:

def findSubstrings(substrings,destString):
    return ', '.join([str([destString.index(x),x]) for x in substrings if x in destString])


Related articles: