简体   繁体   中英

Get a string after a certain substring

How can I get a string after a certain substring:

strings = ["Mayo", "Nice May", "nice May comes", "nice Mayo", "nice Mayo comes"]
substring = "May"

I want to get only the strings that have the word "May" in it and not just contain the sequence "May" .

I have tried these codes:

for x in strings:
    if "May" in x:
        print(x)
for x in strings:
    if x.find("May"):
        print(x)

I want:

Nice May                                                                                                                       

nice May comes

I get:

Mayo                                                                                                                               
Nice May                                                                                                                           
nice May comes                                                                                                                     
nice Mayo                                                                                                                          
nice Mayo comes                                                                                                                    
abcMayabc

Using split() , check if substring is in the elem of strings separated by spaces:

strings = ["Mayo", "Nice May", "nice May comes", "nice Mayo", "nice Mayo comes"]
substring = "May"

for x in strings:
    if substring in x.split(" "): print(x)

OUTPUT :

Nice May
nice May comes

Using list comprehension :

print([x for x in strings if substring in x.split()])

OUTPUT :

['Nice May', 'nice May comes']

Using Regex boundaries.

Ex:

import re

strings = ["Mayo", "Nice May", "nice May comes", "nice Mayo", "nice Mayo comes"]
substring = "May"

for i in strings:
    if re.search(r"\b{}\b".format(substring), i):
        print(i)

Output:

Nice May
nice May comes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM