A simple single line, triple-quoted comment is giving syntax error. Why?

Ben Finney ben+python at benfinney.id.au
Wed Mar 18 20:06:55 EDT 2015


Aditya Raj Bhatt <adityarajbhatt at gmail.com> writes:

> I always do single line comments with # but just for the sake of it I
> tried it with ''' ''' and it gives me a syntax error.

The only comment syntax in Python code is the line-end ‘# …’ syntax.

> In both the interpreter, and the source code text file, doing -
>
> a = 5 '''a comment'''

There is no comment on that line. You have an assignment statement
immediately followed by a string literal, which is invalid syntax.

> http://stackoverflow.com/questions/397148/why-doesnt-python-have-multiline-comments
> which says that there are no 'true' multiline comments in python and
> that all those 'block' comments are actually triple-quoted strings.

That's correct.

> So can someone tell me why a triple-quoted string gives a syntax error
> if only in one line?

Because the string literal – it doesn't matter how it's quoted – can
only appear where the syntax allows for a string literal. It isn't a
comment, so it can't be freely substituted for a comment.

> Can someone also provide a sort of a 'guide' to triple-quoted comments
> in general?

The guide is simple: There are no triple-quoted comments in Python.

If you triple-quote a string literal, it is still a string literal and
must follow all the syntax rules for string literals.

-- 
 \     “[The RIAA] have the patience to keep stomping. They're playing |
  `\         whack-a-mole with an infinite supply of tokens.” —kennon, |
_o__)                                             http://kuro5hin.org/ |
Ben Finney




More information about the Python-list mailing list