Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"%s" % format vs "{0}".format() vs "?" format

In this post about SQLite, aaronasterling told me that

  • cmd = "attach \"%s\" as toMerge" % "b.db" : is wrong
  • cmd = 'attach "{0}" as toMerge'.format("b.db") : is correct
  • cmd = "attach ? as toMerge"; cursor.execute(cmd, ('b.db', )) : is right thing

But, I've thought the first and second are the same. What are the differences between those three?

like image 621
prosseek Avatar asked Sep 11 '10 17:09

prosseek


People also ask

What is %s in string format?

%s acts as a placeholder for the real value. You place the real value after the % operator. This method is often referred to as the "older" way because Python 3 introduced str. format() and formatted string literals (f-strings).

What is the difference between %S and %R in Python?

The difference between %s and %r is that %s uses the str function and %r uses the repr function. You can read about the differences between str and repr in this answer, but for built-in types, the biggest difference in practice is that repr for strings includes quotes and all special characters are escaped.

What does %s mean in Python?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.

What is the difference between %S and %D in Python?

%s acts a placeholder for a string while %d acts as a placeholder for a number.


1 Answers

"attach \"%s\" as toMerge" % "b.db"

You should use ' instead of ", so you don't have to escape.

You used the old formatting strings that are deprecated.

'attach "{0}" as toMerge'.format("b.db")

This uses the new format string feature from newer Python versions that should be used instead of the old one if possible.

"attach ? as toMerge"; cursor.execute(cmd, ('b.db', ))

This one omits string formatting completely and uses a SQLite feature instead, so this is the right way to do it.

Big advantage: no risk of SQL injection

like image 65
leoluk Avatar answered Oct 08 '22 00:10

leoluk