在python Docstring中编写双反斜杠

时间:2021-06-06 02:49:49

标签: python escaping documentation docstring

我正在为带有 clear_stop_character 函数的 python 包编写文档,用户可以在其中在列表中提供额外的停止字符。在我写的文档中:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\\*']).
"""

用户在停止字符之前看到双反斜杠至关重要。但是,构建包的 help() 结果显示:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\*']).
"""

所以,它会误导用户。
顺便说一句,我没有根据之前的问题找到解决方案。
有什么想法吗?

1 个答案:

答案 0 :(得分:3)

\ 在 Python 中是一个转义字符,它告诉 Python 从字面上解释它后面的字符。这意味着 \\ 告诉 Python 从字面上解释第二个 \,从而导致第一个反斜杠未显示的错误。

解决这个问题最简单的方法是使用四个反斜杠:\\\\。这样,Python 会看到第一个反斜杠并按字面解释第二个反斜杠,打印 \。然后,第三个反斜杠将告诉 Python 将第四个反斜杠从字面上解释为 \

只需将代码重写为:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\\\\*']).
"""
相关问题