Fix Python – Split string using a newline delimiter with Python [duplicate]

Question

Asked By – Hariharan

I need to delimit the string which has new line in it. How would I achieve it? Please refer below code.

Input:

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

Output desired:

['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

I have tried the below approaches:

1. output = data.split('\n')
2. output = data.split('/n')
3. output = data.rstrip().split('\n')

Now we will see solution for issue: Split string using a newline delimiter with Python [duplicate]


Answer

str.splitlines method should give you exactly that.

>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

This question is answered By – wim

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0