Back to Blog
Python

Python String splitlines: How to Split on Line Breaks

python string splitlines: Learn how Python's str.splitlines() splits strings at line boundaries, handles universal newlines, and differs from split() - with practical...

string methodsline breakstext processingnewline handlingpython
Illustration of Python's splitlines method splitting a string into lines at newline boundaries.

python string splitlines requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

The str.splitlines() method in Python splits a string at line boundaries and returns a list of lines. It is a built-in method that handles universal newlines, meaning it recognizes \n, \r\n, and \r as line breaks by default. This makes it more robust than split('\n') when processing text from different operating systems.

What splitlines() Does

The str.splitlines() method returns a list of lines in the string, breaking at line boundaries. It recognizes a broader set of line break characters than just \n. By default, it treats \n, \r\n, and \r as line boundaries, along with several other Unicode line separators. This makes it useful for parsing text from files or network protocols that may use different newline conventions.

text = "first line\nsecond line\r\nthird line\rfourth line" print(text.splitlines()) # ['first line', 'second line', 'third line', 'fourth line']

Notice that the line break characters themselves are not included in the output. The method removes them unless you pass keepends=True.

How splitlines() Differs from split()

The split() method with '\n' as the delimiter only splits on that exact character. It does not handle \r\n or \r as line boundaries, and it will produce an empty string for consecutive delimiters. splitlines() treats a sequence of line break characters as a single boundary, which is usually what you want when processing human-readable text.

text = "line1\r\nline2" print(text.split('\n')) # ['line1\r', 'line2'] print(text.splitlines()) # ['line1', 'line2']

So splitlines() removes the \r as well, treating \r\n as a single boundary. This is particularly important when reading files created on Windows, where lines end with \r\n.

Using the keepends Parameter

When keepends=True, the line break characters are retained at the end of each line. This is useful when you need to reconstruct the original text or when the line endings matter for further processing.

text = "one\ntwo\n" print(text.splitlines(keepends=True)) # ['one\n', 'two\n']

Without keepends, the trailing newline is stripped. With keepends, you get the exact segments including the breaks. This is often used when you want to iterate over lines and preserve the original formatting, such as when rewriting a file without changing its line-ending style.

Handling Different Line Break Characters

splitlines() recognizes the following characters as line boundaries:

CharacterDescription
\nLine feed
\r\nCarriage return + line feed
\rCarriage return
\vVertical tab
\fForm feed
\x1cFile separator
\x1dGroup separator
\x1eRecord separator
\x85Next line (C1 control)
\u2028Unicode line separator
\u2029Unicode paragraph separator

This set is defined by the Unicode standard and Python's universal newline handling. In practice, you will most often encounter \n, \r\n, and \r. The method treats each of these as a single boundary, so a \r\n sequence is not split into two lines.

Edge Cases: Empty Strings and Trailing Line Breaks

An empty string returns an empty list, not a list containing an empty string. This is a common point of confusion.

print("".splitlines()) # []

If the string ends with a line break, splitlines() does not add an extra empty line at the end. For example, "a\n".splitlines() returns ['a'], not ['a', '']. This behavior is consistent with how most line-oriented parsers work.

If you need to preserve the trailing empty line, you can use split('\n') or explicitly handle the final segment.

Performance and Memory Considerations

splitlines() returns a list of strings. For very large strings, this means allocating a new string for each line, which can consume memory proportional to the total size of the text. If you only need to process lines one at a time, consider using an iterator over the string instead. Python's io.StringIO or the splitlines() method on a file object (when reading line by line) can be more memory-efficient.

In most applications, the overhead is negligible. But if you are parsing multi-gigabyte log files, you should avoid loading the entire file into memory and then calling splitlines() on it. Instead, iterate over the file object directly, which yields lines lazily.

When to Use splitlines() in Real Code

splitlines() is ideal for parsing text that may come from different operating systems. For example, when reading a file uploaded by a user, you cannot assume it uses \n. Using splitlines() normalizes the line boundaries without manual replacement.

def count_lines(content): return len(content.splitlines())

It is also useful for splitting multi-line strings from configuration files, email bodies, or API responses that use \r\n. Because it handles all common newline styles, you avoid the need to preprocess the text with replace('\r\n', '\n') or similar.

Common Mistakes and Compatibility Notes

One common mistake is assuming splitlines() removes all whitespace. It only removes the line boundary characters, not spaces or tabs at the start or end of lines.

Another is forgetting that splitlines() does not accept a separator argument. Unlike split(), you cannot pass a custom delimiter. If you need to split on a specific character, use split().

Compatibility: splitlines() is available in all Python 3 versions. The behavior is consistent across Python 3.x. In Python 2, the method existed but had some differences with Unicode handling; if you are maintaining legacy code, verify the expected behavior.

python string splitlines: Splitting on Line Breaks | RYUSLOG DEV