The Python Oracle

Split string using a newline delimiter with Python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Melt

--

Chapters
00:00 Split String Using A Newline Delimiter With Python
00:28 Answer 1 Score 15
00:55 Answer 2 Score 3
01:06 Accepted Answer Score 294
01:19 Answer 4 Score 7
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/2204...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #string #python27

#avk47



ACCEPTED ANSWER

Score 294


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



ANSWER 2

Score 15


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

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())



ANSWER 3

Score 7


There is a method specifically for this purpose:

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



ANSWER 4

Score 3


Here you go:

>>> data = """a,b,c
d,e,f
g,h,i
j,k,l"""
>>> data.split()  # split automatically splits through \n and space
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
>>>