10

I came across some Python programs that connect to a MySQL database. In the code, I saw the query in the execute() function is enclosed withing 3 quotations("""). I would like to know the reason for this. I also noticed that 3 quotes are used only while creating, inserting, and updating the table and not while selecting a row.

cursor.execute("""create table student(id char(10),name char(10))""")
cursor.execute("select * from student")

Why?

user1981245
  • 121
  • 1
  • 1
  • 6

1 Answers1

22

It is not needed--the coder who made that just decided to use it for some reason (probably to add emphasis on that part).

A triple-quoted string is just that: a string. It has the same properties as a regular string object. There are only two differences:

  1. It supports multiple lines. This saves you from having to place \n every time you want a newline.
  2. It allows you to have single and double quotes without escaping. This could be useful with SQL commands.

In summary though, a triple-quoted string is a string:

>>> type("""a""")
<type 'str'>
>>> type("a")
<type 'str'>
>>>

and it is not needed in that code.