Search code examples
pythonf-string

Escaping Double Quotations in Python F-String Literal


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')'

Solution

  • The reason you're seeing \' in your final string is because Python produces the repr of a str in the following way:

    • If the string contains neither quotes, encode it in single quotes
    • If the string contains single quotes but not double quotes, enclose it in double quotes
    • If the string contains double quotes but not single quotes, enclose it in single quotes.
    • If the string contains both quotes, enclose it in single quotes, escaping any single quotes present. This is the case you're seeing.

    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.