Docstring具有不一致的前导空格

CAV*_*AVS 2 python docstring python-3.x

在以下代码中:

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)]}
    """
Run Code Online (Sandbox Code Playgroud)

我收到一个错误说:

ValueError: line 4 of the docstring for __main__.read_file has inconsistent leading whitespace: 'Lit!!'
Run Code Online (Sandbox Code Playgroud)

是什么原因引起了这个?

Jim*_*ard 7

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

\nLit!!\n
Run Code Online (Sandbox Code Playgroud)

应该是:

\\nLit!!\\n'
Run Code Online (Sandbox Code Playgroud)

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

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