white_gecko white_gecko - 7 months ago 136
Python Question

python split string but keep delimiter

In python I can easily read a file line by line into a set, just be using:

file = open("filename.txt", 'r')
content = set(file)

each of the elements in the set consists of the actual line and also the trailing line-break.

Now I have a string with multiple lines, which I want to compare to the content by using the normal set operations.

Is there any way of transforming a string into a
just the same way, such, that it also contains the line-breaks?

The question "In Python, how do I split a string and keep the separators?" deals with a similar problem, but the answer doesn't make it easy to adopt to other use-cases.

import re
content = re.split("(\n)", string)

doesn't have the expected effect.


Here's a simple generator that does the job:

content = set(e + "\n" for e in s.split("\n"))

This solution adds an additional newline at the end though.