Skip to content

Instantly share code, notes, and snippets.

@treyhunner

treyhunner/splits.py

Created Mar 22, 2016
Embed
What would you like to do?
splitlines vs. split
import re
import unittest
def splitlines(string, keepends=False):
lines = re.findall('(.*\n|.+$)', string)
return lines if keepends else [x.rstrip('\n') for x in lines]
def split(string):
return re.split('\n', string)
class SplitTests(unittest.TestCase):
strings = [
'a',
'a\n',
'a\nb',
'a\nb\n',
'123\n456\n789',
'123\n456\n789\n',
]
def test_split(self):
for string in self.strings:
self.assertEqual(split(string), string.split('\n'))
def test_splitlines(self):
for string in self.strings:
self.assertEqual(splitlines(string), string.splitlines())
def test_splitlines_with_keepends(self):
for string in self.strings:
self.assertEqual(splitlines(string, True), string.splitlines(True))
if __name__ == "__main__":
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment