Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.
I was trying to format a small JSON for some purposes, like this: '{"all": false, "selected": "{}"}'.format(data) to get something like {"all": false, "selected": "1,2"}
It’s pretty common that the “escaping braces” issue comes up when dealing with JSON.
def preformat(msg):""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{','<<<').replace('}}','>>>')
msg = msg.replace('{','{{').replace('}','}}')
msg = msg.replace('<<<','{').replace('>>>','}')return msg
I recently ran into this, because I wanted to inject strings into preformatted JSON.
My solution was to create a helper method, like this:
def preformat(msg):
""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{', '<<<').replace('}}', '>>>')
msg = msg.replace('{', '{{').replace('}', '}}')
msg = msg.replace('<<<', '{').replace('>>>', '}')
return msg
I stumbled upon this problem when trying to print text, which I can copy paste into a Latex document. I extend on this answer and make use of named replacement fields:
Lets say you want to print out a product of mulitple variables with indices such as
, which in Latex would be $A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$
The following code does the job with named fields so that for many indices it stays readable:
from jinja2 importTemplate
foo =Template('''
#include <stdio.h>
void main() {
printf("hello universe number {{number}}");
}
''')for i in range(2):print(foo.render(number=i))
When you’re just trying to interpolate code strings I’d suggest using jinja2 which is a full-featured template engine for Python, ie:
from jinja2 import Template
foo = Template('''
#include <stdio.h>
void main() {
printf("hello universe number {{number}}");
}
''')
for i in range(2):
print(foo.render(number=i))
So you won’t be enforced to duplicate curly braces as the whole bunch of other answers suggest
回答 14
您可以通过使用原始字符串方法来实现此目的,只需在字符串前添加不带引号的字符’r’。
# to print '{I am inside braces}'print(r'{I am inside braces}')