How is this different from a string?



How is the syntax for a multi-line string different from a string that has two additional quotes inside of it?


In our Codecademy editor, strings and multi-line comments do share the same color: yellow. However! They’re not the same. When Python sees three quotation marks (single or double ) before and after something, it knows to make that a comment, rather than run it as code, if it’s not preceded by assignment to a variable. To illustrate this point, take a look at the example below:

long_string = """
This is just a long string assigned to the long_string variable!
useful for paragraphs
or lines that are very long

This is a multi-line comment.
It spands multiple lines!
It has no variable before it that it is being assigned to,
so it is not a string like above.

FAQ: Learn Python - Python Syntax - Multi-line Strings

It’s probably worth noting that long/docstrings are evaluated as string literals depending on where they are in the code. If they are in the right docstring locations they are added to the __doc__ special dictionary. Otherwise they are ignored by the bytecode interpreter.


Example to support @robmuh’s post above…

>>> def foo():
	"""This is a
lengthy docstring that will be
parsed and bytecode interpreted
by Python.
	return '''foobar'''

>>> foo()
>>> foo.__doc__
'This is a\nlengthy docstring that will be\nparsed and bytecode interpreted\nby Python.'

Note that the return is treated as a normal string.


Actually they are the same. And neither is a comment, but they don’t generate op-codes if not used, it’s dead code.


Would that mean using it in an assignment?


Essentially it’s a “comment” because it doesn’t translate to any op-code
Assignment does (even if the variable isn’t used later, python doesn’t optimize such things, not cpython anyway (the reference implementation, and also most commonly used))


So would the following be a more accurate description?

>>> def foo():
	"""This is a detailed
docstring that will be parsed
and written internally to the
__doc__ attribute of its
function object.

>>> print (foo.__doc__)
This is a detailed
docstring that will be parsed
and written internally to the
__doc__ attribute of its
function object.



Talking about whether docstrings are added by opcodes? That isn’t an unused string, it’s not dead code, it does something. I don’t know whether an opcode is used to add it, but my guess would be yes