Skip to content

preserve_blank_lines=True counts each CRLF as two line breaks #103

Description

@APITester26

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions