Skip to content
Advertisement

Split a string at newline characters

I have a string, say

a = "Show  details1nShow  details2nShow  details3nShow  details4nShow  details5n"

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

The result should be

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

Advertisement

Answer

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'))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement