Inconsistent Whitespace error occurrence when using Python doctest with newline characters

0 votes

Hi all. My question is simple. When you guys write Python doctests, how do you go about introducing the newline characters in the string while testing the process?

Check out the following example:

def remove_newlines(text):
    """
    >>> remove_newlines("line1 \n"
    ...                 "still line 1\r"
    ...                 "now line2 \n"
    ...                 "more line2\n")
    line1 still line1
    now line2 more line2
    """
    return text.replace('\n', '')

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

The output is something like this:

Traceback (most recent call last):
...
ValueError: line 3 of the docstring for NoName has inconsistent leading whitespace: '"'

What am I missing here lads? Using this in a project of mine and I could appreciate all the help that I could get!

Feb 12 in Python by Anirudh
• 2,070 points
118 views

1 answer to this question.

0 votes

Hi. It's pretty simple actually. All you need to do is to escape the backslash and you're good to go.

We already know that the \n is the newline character, right? Also, the docstring itself is a string. Check this out:

def foo():
    """
    print "Hello Edureka! \n";
    """
    pass

The docstring might not contain a completely valid Python statement but see that it contains a quoted string with the newline character in it.

Escaping this character is the key to your problem. Hope this helped!

answered Feb 12 by Nymeria
• 3,520 points

Related Questions In Python

0 votes
1 answer

When I create and remove files rapidly on windows using python I get WindowsError (Error 5)

Here's the short answer: disable any antivirus or ...READ MORE

answered Aug 31, 2018 in Python by charlie_brown
• 7,720 points
144 views
0 votes
1 answer

Need help with Tkinter window formatting using Python

Tkininter comes with the columnspan argument to span the labels ...READ MORE

answered Sep 7, 2018 in Python by ariaholic
• 7,340 points
48 views
0 votes
1 answer

Getting some errors regarding python when using sublime text

I don't know if you still need ...READ MORE

answered Sep 7, 2018 in Python by charlie_brown
• 7,720 points
38 views
0 votes
11 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 337 views
+4 votes
6 answers
0 votes
1 answer

How to fix this? ValueError: invalid literal for int() with base 10 error in Python

The following are totally acceptable in python: passing ...READ MORE

answered Nov 16, 2018 in Python by Nymeria
• 3,520 points
20,190 views
0 votes
1 answer

How to get textual output when using exceptions in Python?

Hi, the answer is pretty simple.  Without the ...READ MORE

answered Jan 17 in Python by Nymeria
• 3,520 points
40 views