16
votes

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
do you want it to be ["show", "details1", "show", "details2", ... ] or ["show details1", "show details2", ... ] - James Brooks
Is it literally '\n', or is it a newline character? - ezod
@ezod: \n is a new-line character - SilentGhost
@Hulk: where are you getting this line from? - SilentGhost
I need it as ["show details1", "show details2", ... ] Also i am getting the above line from a log.... - Hulk

5 Answers

18
votes

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'))
20
votes

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

6
votes

split method:

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

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

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

0
votes

try:

a.split('\n')