Multi-line Comments In Python

13th April 2012

Python doesn't officially support multi-line comments, but there is a way of implementing the same functionality using an existing language construct. Single line comments in Python are written like this:

# This is a single line comment.

Multi-line comments are not officially supported in Python. That said, you can create the same effect in Python by using a multi-line string. Unless it is part of a docstring at the start of a class, function or module then it parsed into a string variable, but nothing is done with it.

  1. '''
  2. This is
  3. a multiline
  4. comment
  5. '''

Because this is a multi-line string it is therefore parsed by Python, so you will need to be careful what you put in it.

Multi-line strings are used when you want to create a string that is split across several lines. If you create one and don't assign it to a variable then it is just thrown away. Multi-line strings can be used in the following way.

  1. multilinestring = '''
  2. This is
  3. a multiline
  4. string
  5. '''
  6. print multilinestring

Python's style guide, PEP8, favors using consecutive single-line comments, and this is also what you'll find in many projects. Text editors usually have a shortcut to do this easily.



Nice article. Helpful information.

Comments are an important part of any programming language.

It gives a better understanding of the program.

shilkaren (Wed, 09/09/2020 - 13:15)

Add new comment

The content of this field is kept private and will not be shown publicly.