Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I split a multi-line string into multiple lines in python?

Tags:

python

I have a multi-line string:

inputString = "Line 1\nLine 2\nLine 3"

I want to have an array, each element will have maximum 2 lines it it as below:

outputStringList = ["Line 1\nLine2", "Line3"]

Can i convert inputString to outputStringList in python. Any help will be appreciated.

like image 440
rajat saxena Avatar asked Jul 01 '26 01:07

rajat saxena


1 Answers

you could try to find 2 lines (with lookahead inside it to avoid capturing the linefeed) or only one (to process the last, odd line). I expanded your example to show that it works for more than 3 lines (with a little "cheat": adding a newline in the end to handle all cases:

import re

s = "Line 1\nLine 2\nLine 3\nline4\nline5"
result = re.findall(r'(.+?\n.+?(?=\n)|.+)', s+"\n")

print(result)

result:

['Line 1\nLine 2', 'Line 3\nline4', 'line5']

the "add newline cheat" allows to process that properly:

    s = "Line 1\nLine 2\nLine 3\nline4\nline5\nline6"

result:

['Line 1\nLine 2', 'Line 3\nline4', 'line5\nline6']
like image 143
Jean-François Fabre Avatar answered Jul 02 '26 14:07

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!