Home > Mobile >  Python add char "\" for no reason
Python add char "\" for no reason

Time:10-09

I have code where I add a number and then create URL for a request

opa_number = '31108100'    
def get_data(opa_number):
        print(opa_number)
        url = "https://phl.carto.com/api/v2/sql?q=SELECT * FROM opa_properties_public WHERE parcel_number = " \
                "'"   self.opa_number   "'"

Please see image

When I'm running this code in console line by line it works as it should

When I'm running this code in debugger it gives me 'https://phl.carto.com/api/v2/sql?q=SELECT * FROM opa_properties_public WHERE parcel_number = \'888020936\'' and add "" around opa_number My question is why Python is adding this symbol and stop it from doing that

CodePudding user response:

This is a consequence of trying to display strings as legal Python string literals. The debugger apparently reimplemented string display, and chose to unconditionally use single-quotes around strings it displays (it doesn't seem to rely directly on str's repr, which would dynamically select the outer quotation mark to be the opposite of the internal ones if only one is used internally; that's what you'd see when such a string was echoed in the interactive interpreter).

Because it's using outer single-quotes, it has to backslash escape the internal single-quotes to make a legal string literal. The backslashes aren't actually there, your code is behaving as expected.

  • Related