Python Python Basics (2015) Python Data Types Strings

Nicolas Bassano
Nicolas Bassano
2,125 Points

Triple quotes to avoid "SyntaxError"..............Python Data Types - Strings video

I understand it but Ive noticed that Kenneth at 02:20 types:

>>> """He's right"""
"He's right"

Wich is the same as....(i think....)

>>> "He's right"
"He's right"

The example above shouldnt give us any problems because we have different quotes on the outside so the triple quotes are not needed.

Am I right??

So triple quotation would be needed if we put it down like this...

>>> '''He's right'''
"He's right"

correct?? or.............

1 Answer

In short, yes.

When you call a docstring, whether """ or ''' pythons interpreter recognizes it as a delimiter value. Using one over the other is really a matter of preference.

Directly from Pep8 documentation:

In Python, single-quoted strings and double-quoted strings are the same. This PEP does not make a recommendation for this. Pick a rule and stick to it. When a string contains single or double quote characters, however, use the other one to avoid backslashes in the string. It improves readability.

For triple-quoted strings, always use double quote characters to be consistent with the docstring convention in PEP 257 .

Will single quoted docstrings work?

Yes they can be used to escape the use of a single quote being used inside of a string.

Why use one over the other?

It really depends on your departments guidelines, if they have specified specific uniformity for ease of reading code than your decision has just been made for you. I would say whatever the case, consistency is key, if you decide to use triple single quotes for certain types of data, then it is beneficial to always use that format.

Nicolas Bassano
Nicolas Bassano
2,125 Points

Thanks Gerald, very informative.