Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Triple-double quote v.s. Double quote

What is the preferred way to write Python doc string?

""" or "

In the book Dive Into Python, the author provides the following example:

def buildConnectionString(params):     """Build a connection string from a dictionary of parameters.      Returns string.""" 

In another chapter, the author provides another example:

def stripnulls(data):     "strip whitespace and nulls"     return data.replace("\00", "").strip() 

Both syntax work. The only difference to me is that """ allows us to write multi-line doc.

Is there any difference other than that?

like image 708
Mingyu Avatar asked Jul 14 '13 21:07

Mingyu


People also ask

What is a triple quotation?

Enclose strings containing both single and double quotes such that no escaping is needed. Enclose multi-line strings.

When would you wrap a string in triple single quotes or triple double quotes?

To create strings that span multiple lines, triple single quotes ''' or triple double quotes """ are used to enclose the string. ''' This string is on multiple lines within three single quotes on either side. ''' """ This string is on multiple lines within three double quotes on either side.

What is the difference between single double and triple quotes?

Using single and double quotes are equivalent. The only difference is when we use an apostrophe or additional quotation marks inside the string, in which case we may need to escape those punctuation(s) using a backslash ( \ ). For example: print("That's great!") print('That\'s great!')

Where are triple quoted strings used?

Triple quoted strings are used as comment by many developers but it is actually not a comment, it is similar to regular strings in python but it allows the string to be in multi-line. You will find no official reference for triple quoted strings to be a comment.


1 Answers

From the PEP8 Style Guide:

  • PEP 257 describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a line by itself, e.g.:

    """Return a foobang  Optional plotz says to frobnicate the bizbaz first. """ 
  • For one liner docstrings, it's okay to keep the closing """ on the same line.

PEP 257 recommends using triple quotes, even for one-line docstrings:

  • Triple quotes are used even though the string fits on one line. This makes it easy to later expand it.

Note that not even the Python standard library itself follows these recommendations consistently. For example,

  • abcoll.py
  • ftplib.py
  • functools.py
  • inspect.py
like image 108
unutbu Avatar answered Oct 05 '22 09:10

unutbu