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 ?
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']