nedla2004 nedla2004 - 4 months ago 10
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

\n
, 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
yellow
green
_surprise!
blue'''

print(a.split('\n')


and should result in:

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


Thanks for any help!

Answer

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 _.

Comments