简体   繁体   中英

Why python is putting “\\” in my string before single quotes

Code where the problem occurs:

    def updateEmpresaSetXEqualsToByCnpj(self, nomeColuna, valor, cnpj):
        query = (r"UPDATE empresa_cliente SET {0} = {1} WHERE cnpj_emp = '{2}';".format(nomeColuna, valor, cnpj))

I'm sending a string, a int and a string. The last param must have single quotes cause SQL SERVER syntax but the python is putting double back slash before each single quotes. eg

UPDATE empresa_cliente SET regime_tributacao_federal = 1 WHERE cnpj_emp = \\'33333222000111\\';

When the correct query should be

UPDATE empresa_cliente SET regime_tributacao_federal = 1 WHERE cnpj_emp = '3333222000111';
r"UPDATE empresa_cliente SET {0} = {1} WHERE cnpj_emp = '{2}';"

r"" suspends escape sequences. If you're working interactively and using r"" don't worry about the double \\\\ when you write to files, it writes only one \\ check that with print .

For the second string:

'UPDATE empresa_cliente SET regime_tributacao_federal = 1 WHERE cnpj_emp = \\\'33333222000111\\\';'

Here's what you've not probably noticed:

>>> "\\\'wwww"
"\\'wwww"
>>> print("\\\'wwww")
\'wwww

If you would, change it to this, it's essentially the same maybe aesthetically better:

"UPDATE empresa_cliente SET regime_tributacao_federal = 1 WHERE cnpj_emp = '33333222000111';"

It's also possible that you're passing you strings to another formatting before you write them elsewhere, check for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM