如何以Pythonic方式按一个或多个\n拆分字符串并保留每个换行符
问题描述
现有如下字符串:
str = "this is text document. which can be represented as below: "
需要按一个或多个\n进行拆分,且在结果列表中保留每个\n的独立实例,期望输出列表为:
["this is text document.", "\n", "\n", "which can be represented as below:", "\n", "\n", "\n"]
请问如何以Pythonic方式实现该需求?
Pythonic实现方案
直接用标准库的re.findall()结合正则表达式就能简洁实现:
import re s = "this is text document.\n\n which can be represented as below:\n\n\n" result = re.findall(r'[^\n]+|\n', s) print(result)
逻辑说明
正则表达式r'[^\n]+|\n'会匹配两种内容:
[^\n]+:一段连续的非换行文本(对应原字符串里的两个段落)\n:单个换行符re.findall()会遍历整个字符串,把所有符合规则的内容按顺序收集到列表中,完全符合需求的输出格式。
内容的提问来源于stack exchange,提问作者Bharat Sharma
相关产品推荐
相关产品推荐

