How should I split HTTP headers in Python? Using .splitlines()
or .split("\r\n")
?
Asked
Active
Viewed 2,985 times
3

Augustin
- 2,444
- 23
- 24

Guy Markman
- 426
- 1
- 4
- 14
1 Answers
6
This SO answer shows that "\r\n" is the correct for the HTTP specification, but it is recommended to be ready to accept only "\n" as well in case you receive a header that doesn't follow the specification.
With that in mind, choose .splitlines
, since the Python docs say:
This method uses the universal newlines approach to splitting lines.
And also explains:
universal newlines
: A manner of interpreting text streams in which all of the following are recognized as ending a line: the Unix end-of-line convention '\n', the Windows convention '\r\n', and the old Macintosh convention '\r'.

Community
- 1
- 1

user2089810
- 82
- 3
-
As mentioned under "universal newlines", `bytes.splitlines()` also splits on `\r`, without any `\n`. I'm not sure that behavior meets the HTTP spec. – djvg Dec 20 '20 at 18:55