Skip to content

Instantly share code, notes, and snippets.

@treyhunner
Created March 22, 2016 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treyhunner/922a4da1d3e0bf674b75 to your computer and use it in GitHub Desktop.
Save treyhunner/922a4da1d3e0bf674b75 to your computer and use it in GitHub Desktop.
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