tags:

views:

166

answers:

5

All,

I have a string in python 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 as ['Show details1', 'Show details2', ..., 'Show details5']

+4  A: 

split method:

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

try:

a.split('\n')
liwp
This doesnt work. i get the result as ['Show details', 'Show details', '']1 more element
Hulk
So ignore the last element? Your input string does have an empty string after the last \n.
Ken
+6  A: 

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

Paul McGuire
out of curiosity, how bad is this performance wise?
Idan K
Paul, I integrated info from the OP's comment to another answer. He doesn't seem to want the "join" part of this...
Peter Hansen
@Idan, it's lots fast. On my machine it splits the 10MB string 'test this\n'*int(1e6)` in 280ms or 28ns per char. Do you have a performance problem involving this function?
Peter Hansen
@Peter - Thanks, no problems. Was just wondering since it does 2 passes on the original string (one for `splitlines` and another for `lower`) but I guess it doesn't change much.
Idan K
A: 

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'))
ddaa
Thanks,this is what i was looking for...........................
Hulk
A: 
 a.split('\n')

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

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

appusajeev