When attempting to escape double quotation marks in a f-string literal in Python, I encounter a strange phenomenon where subsequent single quotes are automatically escaped. This is not what I want, as I intend to pass the "query" string as a SQL Server query which does not process the forward slash as an escape character, but rather as part of the query.
query = f"select apples,\
bananas,\
cranberries,\
durian \
from schema.\"database_name/table_name\" \
where SNAPSHOT_PERIOD = '123' and parameter IN('abc') \
group by POB_ID"
print(query)
Per debugger, resulting string:
'select apples,bananas,cranberries,durian from schema."database_name/table_name" where SNAPSHOT_PERIOD = \'123\' and parameter IN(\'abc\')'
Desired result:
'select apples,bananas,cranberries,durian from schema."database_name/table_name" where SNAPSHOT_PERIOD = '123' and parameter IN('abc')'
The reason you're seeing \'
in your final string is because Python produces the repr
of a str
in the following way:
This way, the repr
is always a valid string literal that when evaluated will produce the original string's content, regardless of the actual content. If the quotes weren't escaped, they would mark the start/end of new string literals, meaning that repr
wouldn't function as intended.
The above processes are totally visual, and your code is functioning as intended - it's just a product of the way the debugger displays the repr
of the string.