python - 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']
解决方案
在这种情况下,最好只使用 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']
推荐阅读
- temperature - 使用树莓派 pico 和 DHT22 传感器作为气象站的 1602 LCD 显示器显示额外小数点出现问题
- kendo-ui - 如何动态分配 Kendo UI Scheduler workDayStart?
- python - Python:带有计数器的for循环和计划增加的增加
- android - 在 Shape Drawable 中调整高度
- c# - 每次迁移中始终包含播种记录
- python - Chrome Devtools 网络 Selenium python
- froala - Froala 附加 Outlook 电子邮件文件导致“出现问题”
- c++ - 如何在模板函数中实现模板类类型?
- vue.js - Vue 路由器警告消息“与参数一起传递,但它们将被忽略”
- solr - 如何从 Apache Solr 下载/导出数据到 CSV 文件?我在 Solr 中创建了集合,我想将数据从 Solr 导出到 CSV