Doctest涉及转义字符

时间:2012-08-01 18:34:10

标签: python doctest

有一个函数fix(),作为输出函数的辅助函数,它将字符串写入文本文件。

def fix(line):
    """
    returns the corrected line, with all apostrophes prefixed by an escape character

    >>> fix('DOUG\'S')
    'DOUG\\\'S'

    """
    if '\'' in line:
        return line.replace('\'', '\\\'')
    return line

启用doctests,我收到以下错误:

Failed example:
    fix('DOUG'S')
Exception raised:
    Traceback (most recent call last):
      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1254, in __run
        compileflags, 1) in test.globs
      File "<doctest convert.fix[0]>", line 1
        fix('DOUG'S')
                  ^

无论我使用的是什么组合,doctest似乎都不想工作,即使函数本身运行完美。怀疑这是doctest在块评论中的结果,但有任何解决此问题的提示。

2 个答案:

答案 0 :(得分:6)

这是你想要的吗?:

def fix(line):
    r"""
    returns the corrected line, with all apostrophes prefixed by an escape character

    >>> fix("DOUG\'S")
    "DOUG\\'S"
    >>> fix("DOUG'S") == r"DOUG\'S"
    True
    >>> fix("DOUG'S")
    "DOUG\\'S"

    """
    return line.replace("'", r"\'")

import doctest
doctest.testmod()

原始字符串是你的朋友......

答案 1 :(得分:1)

首先,如果您实际在交互式解释器中调用函数,则会发生这种情况:

>>> fix("Doug's")
"Doug\\'s"

请注意,您不需要在双引号字符串中转义单引号,并且Python不会在结果字符串的表示中执行此操作 - 只有反斜杠才会被转义。

这意味着正确的文档字符串应该是(未经测试的!)

"""
returns the corrected line, with all apostrophes prefixed by an escape character

>>> fix("DOUG'S")
"DOUG\\\\'S"

"""

我会为此docstring使用原始字符串文字,以使其更具可读性:

r"""
returns the corrected line, with all apostrophes prefixed by an escape character

>>> fix("DOUG'S")
"DOUG\\'S"

"""