非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
虽然不是更好,但仅供参考,您也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
例如,当有人想要打印{argument}时,它会很有用。它可能比“{{}}”更可读。format(“argument”)
注意,在Python 2.7之后省略了参数位置(例如{}而不是{0})
其他回答
OP撰写了以下评论:
我试图为某些目的格式化一个小JSON,例如:“{”all“:false,”selected“:”{}“}”。格式化(数据)以获得类似于{”all:false,“selected”:“1,2”}的内容
在处理JSON时,“转义括号”问题很常见。
我建议这样做:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
它比替代方案更干净,即:
'{{"all": false, "selected": "{}"}}'.format(data)
当json字符串比示例更复杂时,使用json库无疑是更好的选择。
我最近遇到了这个问题,因为我想将字符串注入到预先格式化的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
然后,您可以执行以下操作:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
如果性能不是问题,则获取完成的作业。
您想用字符{或}格式化字符串
你只需要把它们加倍。
格式{带有f“{{”,}带有f‘}}”
So :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
输出:
你好,鲍勃!我想打印}和{或{}
对于确切的示例,OR:
number = 42
print(f'{{Hello}} {number}')
将打印:
{你好}42
如果要仅打印大括号的一侧:
a=3
print(f'{"{"}{a}')
>>> {3
如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'