Python tips-substring search

Source: Internet
Author: User

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])
 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.