python 3中列表中的特定模式字符串
要求:使用正则表达式只需要从输入列表中获取特定字符串,即“-”和“*”符号之间的字符串。下面是代码片段python 3中列表中的特定模式字符串,python,regex,Python,Regex,要求:使用正则表达式只需要从输入列表中获取特定字符串,即“-”和“*”符号之间的字符串。下面是代码片段 ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.'] ZTon = [ line.strip() for line in ZTon] print
ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
ZTon = [ line.strip() for line in ZTon]
print (ZTon)
r = re.compile(".^--")
portion = list(filter(r.match, ZTon)) # Read Note
print (portion)
预期答复:
['and preferably only one','right']
使用正则表达式
import re
ZTon = ['one-- and preferably only one --obvious', " Hello World", 'Now is better than never.', 'Although never is often better than *right* now.']
pattern=r'(--|\*)(.*)\1'
l=[]
for line in ZTon:
s=re.search(pattern,line)
if s:l.append(s.group(2).strip())
print (l)
# ['and preferably only one', 'right']
印刷品:
['and preferably only one', 'right']
到目前为止你试过什么?你在哪里被卡住了?请分享你试图获取字符串的代码,而不是使用
strip()
.ZTon=[“一个——最好只有一个——显而易见”,“你好,世界”,“现在比从来都好”,“虽然从来都比现在好。”]ZTon=[line.strip()代表ZTon中的行]print(ZTon)r=re.compile(.^--)partment=list(过滤器(r.match,ZTon))#读取注释打印(部分)
['and preferably only one', 'right']