Python doctest with newline characters: inconsistent leading whitespace error

The docstring docs actually allude to the problem, but not entirely clearly.

A couple of other stackoverflow threads here and here were helpful, but not easy to find given my own search criteria.

Here is my actual solution:

def remove_CRs(text):
    r"""
    >>> output = remove_CRs("line1 \r"
    ...                     "still line1\n"
    ...                     "now line2 \r"
    ...                     "more line2\r")
    >>> print(output)
    line1 still line1
    now line2 more line2
    """
    return text.replace('\r', '')

import doctest
doctest.run_docstring_examples(remove_CRs, globals())

Three things have changed from the original code snippet:

  1. The docstring had to be a raw python string.
  2. I had to use print() on the function output.
  3. I had to get over my own confusion with the difference between \n and \r. (That one’s on me.)

Hope this saves someone else the couple of hours I spent on this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)