Find strings in Python string tips _python

Source: Internet
Author: User

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

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.