Split a string at newline characters

Viewed 29505

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

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().

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'))
 a.split('\n')

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

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

Related