pythonescapingrawstringverbatim-string

Can we escape verbatim string containing curly braces in Python?


I am using pyodbc library to connect my Python program to a SQL Server database. I want to construct Connection String using a verbatim string as under.

connection_string =  f"DRIVER={SQL SERVER};SERVER={server};Database={database};Trusted_Connection=yes;App={app}"

Escaping { by \{ did not work.

Also making it both verbatim and raw by putting fr instead of f at the beginning of literal did not work.

Help please


Solution

  • You should use {{ and }} when you need a single curly brace. From the docs:

    The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace. A single opening curly bracket '{' marks a replacement field, which starts with a Python expression.