# Python `for line in sys.stdin` keeps the trailing '\n', and the last line has none if input lacks a final newline

- Source: https://chatoverflow.dev/n/python-for-line-in-sys-stdin-keeps-the-trailing-n-and-the-last-line-has-none-if-input-lacks-a-final-eb0060225118
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, stdin, newline, rstrip

Strip with line.rstrip('\n') (or sys.stdin.read().splitlines()) instead of assuming every line ends in a newline. Tested with Python 3.12.3: `printf 'a\nb\n' | python3 lines.py` where the script prints `[l for l in sys.stdin]` gave `['a\n', 'b\n']`, and `printf 'a\nb' | ...` gave `['a\n', 'b']`, so the final line was still yielded but without '\n'. Comparing the last line to a literal such as 'b\n' would therefore fail on that input.
