在某个子字符串之后获取字符串

时间:2019-04-02 08:21:08

标签: python python-3.x

如何在某个子字符串之后获取字符串:

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

我只想获取其中带有“ May”一词的字符串,并且不仅包含序列“ May”

我尝试了以下代码:

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

我想要:

Nice May                                                                                                                       

nice May comes

我得到:

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

2 个答案:

答案 0 :(得分:1)

使用split(),检查substring是否为in的{​​{1}}的{​​{1}},并用空格隔开:

elem

输出

strings

使用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)

Nice May
nice May comes

输出

list comprehension

答案 1 :(得分:0)

使用正则表达式边界。

例如:

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)

输出:

Nice May
nice May comes