About this articleThis article was generated using an automated workflow powered by generative AI. String line splitting was verified against the official Python documentation, and the code examples were executed using synthetic text.
Verification status: Code examples successfully executed on Python 3.12.14. Actual file loading and WordPress display have not been verified.
How many lines does Python splitlines produce with a trailing newline? Distinguishing empty inputs from blank lines
Suppose you count the number of lines received from task notes exported by different tools. If a single line reading "Inspected" arrives with a trailing newline, counting it as two lines makes it look like there is an empty task item at the end. Conversely, treating both an empty string and an input with a single newline as zero lines erases the fact that a blank line was sent. First, observe the input as a string and choose the method that suits your line-counting objectives.
Comparing four types of inputs
Save the following program as notes_lines.py and run python3 notes_lines.py in Python 3.12. No additional standard libraries or files are required.repr() displays newlines with escape sequences, making trailing newlines and remaining separators visible in the input.
samples = {
"空の入力": "",
"改行だけ": "\n",
"末尾に改行": "点検済み\n",
"途中に空行": "点検済み\r\n\r\n送付待ち\r\n",
}
for label, value in samples.items():
print(f"{label}: {value!r}")
print(" splitlines:", value.splitlines())
print(" split:", value.split("\n"))
空の入力: '' splitlines: [] split: [''] 改行だけ: '\n' splitlines: [''] split: ['', ''] 末尾に改行: '点検済み\n' splitlines: ['点検済み'] split: ['点検済み', ''] 途中に空行: '点検済み\r\n\r\n送付待ち\r\n' splitlines: ['点検済み', '', '送付待ち'] split: ['点検済み\r', '\r', '送付待ち\r', '']
splitlines() treats a trailing newline as the end of the preceding line. Therefore, even if a single newline follows "Inspected", the output contains only one element. If there is only a newline, it returns a single empty line. If consecutive newlines occur in the middle, the intermediate blank lines remain as ''.
split("\n") uses a specified single character as a delimiter and creates elements before and after the delimiter. An empty element is created after a trailing delimiter, and for inputs containing CRLF, \r remains at the end of each element. For instance, if the input specification is to "save all fields separated by LF", this trailing empty element is also meaningful.
Adding just one trailing newline
Change the "trailing newline" value to "点検済み\n\n" and run again.splitlines() output is ['点検済み', ''] because the first newline terminates the inspected line, and the next newline terminates the blank line below it. When using it for line counts, you can distinguish between a normal single line and two lines where a blank line actually exists in this manner.
If you unconditionally strip newlines before splitting, you cannot restore this distinction. For example, strip() also removes edge whitespace in addition to newlines. When the indentation or blank lines of inspection items are meaningful, check repr() and the element count before modifying the input.
Inspecting newline types
str.splitlines() recognizes standalone CRs and Unicode line separators, in addition to LF and CRLF. For data where systems have an agreement that only LF is the record terminator, explicitly specify the delimiter according to the input specification. The handling of empty elements and delimiters differs between displaying general text on a screen and machine-reading a fixed delimiter format.
If you want to split line contents while also checking which type of newline was present, you can try splitlines(keepends=True). In the "blank lines in between" example above, CRLF remains in each element. Verifying the result with an expected short example makes it easier to trace differences before moving on to actual input. For formats like CSV where records can contain newlines inside quotes, count the records using a parser that supports the format.
Official Documentation
- Python 3.12 Built-in Types str.splitlines and str.split describe the handling of empty strings, trailing newlines, and delimiters.
