Docstring具有不一致的前导空格

时间:2016-12-01 18:44:40

标签: python python-3.x docstring

在以下代码中:

def read_file(filename):
    """
    >>> read_file('text.txt')
    {'Donald Trump': [('Donald Trump', 'Join me live in Springfield, Ohio!\nLit!!\n', 1477604720, 'Twitter for iPhone', 5251, 1895)]}
    """

我收到错误说:

ValueError: line 4 of the docstring for __main__.read_file has inconsistent leading whitespace: 'Lit!!'

任何想法导致了什么?

1 个答案:

答案 0 :(得分:7)

转义文档字符串中的所有反斜杠。那就是:

\nLit!!\n

应改为:

\\nLit!!\\n'

或者你可以将docstring作为原始字符串提供,而不用担心反斜杠:

r"""
>>> read_file('text.txt')
{'Donald Trump': [('Donald Trump', 'Join me live in Springfield, Ohio!\nLit!!\n', 1477604720, 'Twitter for iPhone', 5251, 1895)]}
"""