You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何以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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:45:59