Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing double backslash in python Docstring

Tags:

I am writing documentations for a python package with a clear_stop_character function, in which users can provide extra stop-chars in a list. In the documentation I have written:

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

It is crucial for the users to see the double backslash before the stop-char. However, the help() outcome of the built package shows:

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

So, it will be misleading for the users.
BTW, I did not find a solution based on the previous questions.
Any ideas?

like image 459
maaniB Avatar asked Jun 06 '21 02:06

maaniB


People also ask

How do you add a backward slash to a string in Python?

Use two backslashes to represent a backslashUse the syntax "\\" within the string literal to represent a single backslash.

How does Python handle backslash?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

Do you need to escape backslash in Python?

A raw string can be used by prefixing the string with r or R , which allows for backslashes to be included without the need to escape them. For example: print(r"Backslashes \ don't need to be escaped in raw strings.")

What is multiline docstring in Python?

Multi-line docstrings consist of a summary line just like a one-line docstring, followed by a blank line, followed by a more elaborate description. The summary line may be used by automatic indexing tools; it is important that it fits on one line and is separated from the rest of the docstring by a blank line.


1 Answers

\ in Python is an escape character which tells Python to interpret the character following it literally. This means that \\ tells Python to interpret the second \ literally, thus causing the error where the first backslash is not displayed.

The simplest solution to this problem is to use four backslashes: \\\\. This way, Python sees the first backslash and interprets the second one literally, printing \. Then, the third backslash will tell Python to interpret the fourth one literally like \.

Simply rewrite your code as:

"""
stoplist (list, default empty): Accepts a list of extra stop characters,
            should escape special regex characters (e.g., stoplist=['\\\\*']).
"""
like image 60
q9i Avatar answered Sep 30 '22 17:09

q9i