With preserve_blank_lines=True, a Windows line ending (\r\n) is counted as two line endings, so every CRLF in the input adds an extra blank line to the output.
>>> import titlecase
>>> titlecase.titlecase("Line1\r\n\r\nLine2", preserve_blank_lines=True)
'Line1\n\n\n\nLine2' # expected: 'Line1\n\nLine2'
| input |
actual |
expected |
'a\r\nb' (no blank line) |
'A\n\nB' |
'A\nB' |
'Line1\r\nLine2\r\nLine3' |
'Line1\n\nLine2\n\nLine3' |
'Line1\nLine2\nLine3' |
'Line1\r\n\r\nLine2' (one blank line) |
'Line1\n\n\n\nLine2' |
'Line1\n\nLine2' |
LF input is handled correctly: 'a\nb' gives 'A\nB' and 'a\n\nb' gives 'A\n\nB'.
The cause is in titlecase/__init__.py, in the preserve_blank_lines branch:
if preserve_blank_lines:
lines = regex.split('[\r\n]', text)
else:
lines = regex.split('[\r\n]+', text)
\r\n is two characters but one line ending, so split produces an empty element between the two, and joining the pieces with "\n" turns it into a blank line. The default branch (preserve_blank_lines=False) uses [\r\n]+ and is not affected.
This reaches any caller that passes CRLF text to the library API: HTTP response bodies, subprocess output, files read with newline='', output from Windows tools. The CLI is not affected, because it opens files in text mode and universal newlines convert CRLF to LF before titlecase sees the text.
A fix would be to treat one line ending as one separator, for example:
lines = regex.split(r'\r\n|\r|\n', text)
TestBlankLines.test_complex_blanks only uses \n, so this path currently has no coverage.
The same behaviour is present in the 2.4.1 release, so it is not specific to main.
With
preserve_blank_lines=True, a Windows line ending (\r\n) is counted as two line endings, so every CRLF in the input adds an extra blank line to the output.'a\r\nb'(no blank line)'A\n\nB''A\nB''Line1\r\nLine2\r\nLine3''Line1\n\nLine2\n\nLine3''Line1\nLine2\nLine3''Line1\r\n\r\nLine2'(one blank line)'Line1\n\n\n\nLine2''Line1\n\nLine2'LF input is handled correctly:
'a\nb'gives'A\nB'and'a\n\nb'gives'A\n\nB'.The cause is in
titlecase/__init__.py, in thepreserve_blank_linesbranch:\r\nis two characters but one line ending, sosplitproduces an empty element between the two, and joining the pieces with"\n"turns it into a blank line. The default branch (preserve_blank_lines=False) uses[\r\n]+and is not affected.This reaches any caller that passes CRLF text to the library API: HTTP response bodies, subprocess output, files read with
newline='', output from Windows tools. The CLI is not affected, because it opens files in text mode and universal newlines convert CRLF to LF beforetitlecasesees the text.A fix would be to treat one line ending as one separator, for example:
TestBlankLines.test_complex_blanksonly uses\n, so this path currently has no coverage.The same behaviour is present in the 2.4.1 release, so it is not specific to
main.