Python中如何按引号添加换行?技术咨询
实现引号内容单独换行的正则方案
当然可以用正则表达式搞定这个需求!这是个很典型的字符串匹配替换场景,咱们一步步来实现:
核心思路
我们需要匹配所有被双引号包裹的文本块,然后在每个块的前后添加换行符,让每个引号内的内容单独占一行。
完整代码示例
import re # 你的原始文本 raw_text = '''"Going to school. Taking a few courses and playing basketball. Got a new puppy." "Going to school. I bought a new backpack yesterday. Got a new cat. I did my homework as well." "Going to school. Brought lunch today."''' # 执行正则替换 formatted_text = re.sub(r'"([^"]+)"', r'\n"\1"\n', raw_text) # 移除首尾可能多余的换行(可选操作) formatted_text = formatted_text.strip() # 打印结果 print(formatted_text)
正则表达式详解
- 匹配规则
r'"([^"]+)"':":精准匹配开头的双引号([^"]+):用括号捕获引号内的所有内容([^"]表示匹配任意非引号字符,+表示匹配至少一个)":精准匹配结尾的双引号
- 替换规则
r'\n"\1"\n':\n:添加换行符\1:引用前面捕获到的引号内文本,保证内容不会丢失- 整体效果就是把每个引号块前后加上换行,让它单独占一行
最终效果
运行代码后,输出会变成:
"Going to school. Taking a few courses and playing basketball. Got a new puppy."
"Going to school. I bought a new backpack yesterday. Got a new cat. I did my homework as well."
"Going to school. Brought lunch today."
如果之后你还想让引号内的每个句子也单独换行(比如句号后换行),可以再叠加一层正则替换,但根据你的需求,上面的代码已经完美解决问题啦。
内容的提问来源于stack exchange,提问作者John Veridan
相关产品推荐
相关产品推荐

