[英]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" . 我只想获取其中包含单词“ May”的字符串, 而不仅仅是包含序列“ 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: 使用split()
,检查substring
是否in
用空格分隔的strings
的elem
中:
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
: 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.