Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Python give any error when quotes around a string do not match?

I've started learning Python recently and I don't understand why Python behaves like this:

 >>> "OK" 'OK' >>> """OK""" 'OK' >>> "not Ok'   File "<stdin>", line 1     "not Ok'            ^ SyntaxError: EOL while scanning string literal >>> "not OK""" 'not OK' 

Why doesn't it give an error for the last statement as the number of quotes does not match?

like image 680
W. R. Avatar asked Sep 03 '20 15:09

W. R.


People also ask

Do quotation marks matter in Python?

Key Differences Between Single and Double Quotes in Python Single quotes for anything that behaves like an Identifier. Double quotes generally we used for text. Single quotes are used for regular expressions, dict keys or SQL. Double quotes are used for string representation.

What do triple quotes surrounding a string signify Python?

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.

Do single and double quotes matter Python?

In Python, such sequence of characters is included inside single or double quotes. As far as language syntax is concerned, there is no difference in single or double quoted string. Both representations can be used interchangeably.


1 Answers

The final """ is not recognized as a triple-quotation, but a single " (to close the current string literal) followed by an empty string ""; the two juxtaposed string literals are concatenated. The same behavior can be more readily recognized by putting a space between the closing and opening ".

>>> "not OK" "" 'not OK' 
like image 143
chepner Avatar answered Sep 27 '22 20:09

chepner