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, 2019 in Python by Anirudh
• 2,080 points

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";

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, 2019 by Nymeria
• 3,540 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,760 points
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 aryya
• 7,350 points
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,760 points
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, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 953 views
0 votes
0 answers
+4 votes
6 answers
+1 vote
3 answers

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

The error message invalid literal for int() ...READ MORE

answered Apr 29 in Python by warrenfelsh
• 140 points
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, 2019 in Python by Nymeria
• 3,540 points