Hulk
Hulk

Reputation: 34170

Split a string at newline characters

I have a string, say

a = "Show  details1\nShow  details2\nShow  details3\nShow  details4\nShow  details5\n"

How do we split the above with the delimiter \n (a newline)?

The result should be

['Show  details1', 'Show  details2', ..., 'Show  details5']

Upvotes: 18

Views: 31174

Answers (6)

wh0am1
wh0am1

Reputation: 81

Had a similar issue. I was getting csv data in this format

["User Name\r\nEmail\r\nContact\nAddress", "Name 1\r\[email protected]\r\n+12345657890\r\nSample Address", "Name 2\r\[email protected]\r\n+21345657890\r\nSample Address 2", ]

I used [i.splitlines() for i n data] to convert in list of list

>>> data = ["User Name\r\nEmail\r\nContact\nAddress", "Name 1\r\[email protected]\r\n+12345657890\r\nSample Address", "Name 2\r\[email protected]\r\n+21345657890\r\nSample Address 2", ]
>>> [i.splitlines() for i in data]
[['User Name', 'Email', 'Contact', 'Address'], ['Name 1', '[email protected]', '+12345657890', 'Sample Address'], ['Name 2', '[email protected]', '+21345657890', 'Sample Address 2']]

Upvotes: 0

appusajeev
appusajeev

Reputation: 2299

 a.split('\n')

would return an empty entry as the last member of the list.so use

a.split('\n')[:-1]

Upvotes: 1

ddaa
ddaa

Reputation: 54464

If you are concerned only with the trailing newline, you can do:

a.rstrip().split('\n')

See, str.lstrip() and str.strip() for variations.

If you are more generally concerned by superfluous newlines producing empty items, you can do:

filter(None, a.split('\n'))

Upvotes: 18

SilentGhost
SilentGhost

Reputation: 319571

split method:

a.split('\n')[:-1]

Upvotes: 6

PaulMcG
PaulMcG

Reputation: 63709

Use a.splitlines(). This will return you a list of the separate lines. To get your "should be" result, add " ".join(a.splitlines()), and to get all in lower case as shown, the whole enchilada looks like " ".join(a.splitlines()).lower().

Upvotes: 22

liwp
liwp

Reputation: 6926

try:

a.split('\n')

Upvotes: 0

Related Questions