How can I include special characters (tab, newline) in a python doctest result string?
I've gotten this to work using literal string notation for the docstring:
def join_with_tab(iterable): r""" >>> join_with_tab(['1', '2']) '1\t2' """ return '\t'.join(iterable)if __name__ == "__main__": import doctest doctest.testmod()
It's the raw heredoc string notation (r"""
) that did the trick:
# filename: dedupe.pyimport re,doctestdef dedupe_whitespace(s,spacechars='\t '): r"""Merge repeated whitespace characters. Example: >>> dedupe_whitespace('Black\t\tGround') #doctest: +REPORT_NDIFF 'Black\tGround' """ for w in spacechars: s = re.sub(r"("+w+"+)", w, s) return sif __name__ == "__main__": doctest.testmod()
TL;DR: Escape the backslash, i.e., use \\n
or \\t
instead of \n
or \t
in your otherwise unmodified strings;
You probably don't want to make your docstrings raw as then you won't be able to use any Python string escapes including those you might want to.
For a method that supports using normal escapes, just escape the backslash in the backslash-character escape so after Python interprets it, it leaves a literal backslash followed by the character which doctest
can parse.