首页 > 解决方案 > Python - 捕获字符串开头和结尾之间的所有字符串

问题描述

如何在给定开始和结束字符的情况下将所有字符串捕获到列表中?

这是我尝试过的:

import re

sequence = "This is start #\n hello word #\n #\n my code#\n this is end"

query = '#\n'
r = re.compile(query)
findall = re.findall(query,sequence)
print(findall)

这给出了:

['#\n', '#\n', '#\n', '#\n']

寻找如下输出:

[' hello word ',' my code']

标签: pythonpython-3.x

解决方案


在这种情况下,最好只使用 string 函数.split()并将其#\n作为要拆分的内容传递。s.strip()您可以使用并过滤掉空行来检查长度。如果由于某种原因您不想要第一个和最后一个部分,您可以使用切片[1:-1]来删除它们。

sequence = "This is start #\n hello word #\n #\n my code#\n this is end"
print(sequence.split("#\n"))
# ['This is start ', ' hello word ', ' ', ' my code', ' this is end']

print([s.strip() for s in sequence.split("#\n") if s.strip()])
# ['This is start', 'hello word', 'my code', 'this is end']

print([s.strip() for s in sequence.split("#\n") if s.strip()][1:-1])
# ['hello word', 'my code']

推荐阅读