[英]Get a string after a certain substring
如何在某個子字符串之后獲取字符串:
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
使用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)
輸出 :
Nice May
nice May comes
使用list comprehension
:
print([x for x in strings if substring in x.split()])
輸出 :
['Nice May', 'nice May comes']
使用正則表達式邊界。
例如:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.