Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

split by multiple \n and retaining same

I have string as given below . Which I want to split by one or more \n and maintain the occurrence of \n in resultant list .
Input string

str = "this is text document.\n\n which can be represented as below:\n\n\n"

output list

["this is text document.", "\n", "\n", "which can be represented as below:", "\n", "\n", "\n"]

How this can be done in pythonic way ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance

>Solution :

A regex of an alternation pattern would be a fitting tool for the task:

import re

s = "this is text document.\n\n which can be represented as below:\n\n\n"
print(re.findall(r'\n|.+', s))

This outputs:

['this is text document.', '\n', '\n', ' which can be represented as below:', '\n', '\n', '\n']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading