Docstring 的前导空格不一致

Docstring has inconsistent leading whitespace

在下面的代码中:

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!!'

知道是什么原因造成的吗?

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

\nLit!!\n

应该改为:

\nLit!!\n'

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

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