3 ms·
str.split() function does the same: >>> s = "line1\nline2\rline3\r\nline4\vline5\x1dhello" >>> s.split() ['line1', 'line2', 'line3', 'line4', 'line5', 'hello'
by cuckoos-jicamas 1y ago
str.split() function does the same:
>>> s = "line1\nline2\rline3\r\nline4\vline5\x1dhello"
>>> s.split()
['line1', 'line2', 'line3', 'line4', 'line5', 'hello']
>>> s.splitlines()
['line1', 'line2', 'line3', 'line4', 'line5', 'hello']
But split() has sep argument to define delimiter according which to split the string.. In which case it provides what you expected to happen:
>>> s.split('\n')
['line1', 'line2\rline3\r', 'line4\x0bline5\x1dhello']
In general you want this:
>>> linesep_splitter = re.compile(r'\n|\r\n?')
>>> linesep_splitter.split(s)
['line1', 'line2', 'line3', 'line4\x0bline5\x1dhello']
- gertlex 1y agosplitlines() is sometimes nice for adhoc parsing (of well behaved stuff...) because it throws out whitespace-only lines from the resulting list of strings. #1 use-case of that for me is probably just avoiding the cases where there's a trailing newline character in the output of a command I ran by subprocess.
- roelschroeven 1y agoIn that example str.split() has the same result as str.splitlines(), but it's not in general the same, even without custom delimiter. str.split() splits on runs of consecutive whitespace, any type of whitespace, including tabs and spaces which splitlines() doesn't do. >>> 'one two'.split() ['one', 'two'] >>> 'one two'.splitlines() ['one two'] split() without custom delimiter also splits on runs of whitespace, which splitline() also doesn't do (except for \r\n because that combination counts as one line ending): >>> 'one\n\ntwo'.split() ['one', 'two'] >>> 'one\n\ntwo'.splitlines() ['one', '', 'two']