Home > database >  python string formatting single quotes and double quotes
python string formatting single quotes and double quotes

Time:12-02

I have a variable state = 'PA'. I am trying to generate a string as follows. I would like add single quotes on the state within a string. Also, I want to use this .format method because I will change this state later.

'select * from table where "state" = 'PA''

Currently, I could only be able to generate this 'select * from table where "state" = PA'

using the following code:

'select * from table where "state" = {}'.format(state)

CodePudding user response:

You can escape the single quotes around the format specifier like this:

>>> s = 'select * from table where "state" = \'{}\''.format(state)
>>> print(s)
select * from table where "state" = 'PA'
  • Related