view raw
nedla2004 nedla2004 - 9 months ago 35
Python Question

Python Split Unless Next Character Is Something

I am using Python 3.5, and I would like to split a string by the character

, or new line. however if the line starts with a underscore, for example, it should put that line with the one above it. I need the solution to work for all characters, not just underscore. It should work like this:

a = '''red


and should result in:

['red', 'yellow', 'green\n_surprise', 'blue']

Thanks for any help!


It's pretty easy using regular expressions:

import re
re.split('\n(?!_)', a)
# ['red', 'yellow', 'green\n_surprise!', 'blue']

This regex litterally means split by \n not followed by _.