Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Newbie Python question about strings with parameters: "%%s"?

Tags:

python

string

I'm trying to figure out what the following line does exactly - specifically the %%s part?

cursor.execute('INSERT INTO mastertickets (%s, %s) VALUES (%%s, %%s)'%sourcedest, (self.tkt.id, n))

Any good mini-tutorial about string formatting and inserting variables into strings with Python?

like image 621
Epaga Avatar asked Nov 25 '08 13:11

Epaga


People also ask

What is S %% in Python?

The % symbol is used in Python with a large variety of data types and configurations. %s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string. It is used to incorporate another string within a string.

How would you confirm that 2 strings have the same identity in Python?

How would you confirm that 2 strings have the same identity? The is operator returns True if 2 names point to the same location in memory. This is what we're referring to when we talk about identity. Don't confuse is with ==, the latter which only tests equality.

What does * do to strings in Python?

Joining of two or more strings into a single one is called concatenation. The + operator does this in Python. Simply writing two string literals together also concatenates them. The * operator can be used to repeat the string for a given number of times.

What are Python strings explain in detail with example?

String is a collection of alphabets, words or other characters. It is one of the primitive data structures and are the building blocks for data manipulation. Python has a built-in string class named str . Python strings are "immutable" which means they cannot be changed after they are created.


1 Answers

The %% becomes a single %. This code is essentially doing two levels of string formatting. First the %sourcedest is executed to turn your code essentially into:

cursor.execute('INSERT INTO mastertickets (BLAH, FOO) VALUES (%s, %s)', (self.tkt.id, n))

then the db layer applies the parameters to the slots that are left.

The double-% is needed to get the db's slots passed through the first string formatting operation safely.

like image 83
Ned Batchelder Avatar answered Oct 28 '22 20:10

Ned Batchelder