简体   繁体   中英

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

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.

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