Created
March 22, 2016 17:20
-
-
Save treyhunner/922a4da1d3e0bf674b75 to your computer and use it in GitHub Desktop.
splitlines vs. split
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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