nedla2004 nedla2004 - 1 year ago 72
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!

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download