Gre*_*ill 1802

你需要加倍{{}}:

>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '
Run Code Online (Sandbox Code Playgroud)

以下是格式字符串语法Python文档的相关部分:

格式字符串包含由大括号括起的"替换字段" {}.大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中.如果你需要在文字文本中包含一个大括号字符,可以通过加倍来转义它:{{}}.

  • 因此,如果你想打印"{42}",你可以使用"{{{0}}}".format(42)`! (233认同)
  • "{{".format()和"}}".format()打印单个花括号.在您的示例中:print"{{something {{}} {0}".format(42)将打印"{something {} 42". (14认同)
  • 如果你想要一个大括号怎么样?`"{something {} {value}".format(42)`不起作用. (7认同)
  • @Imray:`{0}`指的是`.format()`的第一个参数.只要给`.format()`提供相同数量的参数,就可以打印多个值,如`{0} {1} {2}`.有关大量示例,请参阅http://docs.python.org/library/string.html#format-examples. (5认同)
  • “{0}”是什么意思? (2认同)
  • @Mithril:您仍然需要*双*每个大括号。所以你可能需要 `f'/blah/blah/{{{{ strftime(...) }}}/blah'` 或其他东西。 (2认同)

Nic*_*ens 86

{您想要使用字符或来格式化字符串}

你只需要将它们加倍即可。

格式{f'{{'}f'}}'

所以 :

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
Run Code Online (Sandbox Code Playgroud)

输出 :

你好鲍勃!我想打印 } 和 { 或 { }

或者对于确切的示例:

number = 42
print(f'{{Hello}} {number}')
Run Code Online (Sandbox Code Playgroud)

将打印:

{你好} 42

最后 :

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
Run Code Online (Sandbox Code Playgroud)

{你好} {42} 42 {鲍勃} 鲍勃


Kam*_*iel 65

你通过加倍括号来逃避它.

例如:

x = "{{ Hello }} {0}"
print x.format(42)
Run Code Online (Sandbox Code Playgroud)


twa*_*lig 39

OP写了这样的评论:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
Run Code Online (Sandbox Code Playgroud)

在处理JSON时出现"逃避大括号"问题是很常见的.

我建议这样做:

'{{"all": false, "selected": "{}"}}'.format(data)
Run Code Online (Sandbox Code Playgroud)

它比替代品更清洁,它是:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
Run Code Online (Sandbox Code Playgroud)

'{"all": false, "selected": "{}"}'.format(data)当JSON字符串比示例更复杂时,使用库肯定是更可取的.

  • wizzwizz4:好点。从Python 3.6开始,字典按插入顺序排序,因此这不是问题。2.7和3.5之间的Python版本可以使用collections库中的OrderedDict。 (2认同)

div*_*nex 34

Python 3.6+(2017)

在最近的Python版本中,人们会使用f-strings(另请参阅PEP498).

使用f-strings,应该使用double {{}}

n = 42  
print(f" {{Hello}} {n} ")
Run Code Online (Sandbox Code Playgroud)

产生所需的

 {Hello} 42
Run Code Online (Sandbox Code Playgroud)

如果您需要在括号中解析表达式而不是使用文字文本,则需要三组括号:

hello = "HELLO"
print(f"{{{hello.lower()}}}")
Run Code Online (Sandbox Code Playgroud)

产生

{hello}
Run Code Online (Sandbox Code Playgroud)

  • 从 `my_greet = "HELLO"` 中,您可以得到 `{hello}` 作为输出,仅使用 2 组括号,以及 `print(f"{ {my_greet.lower()} }")`。只需在括号之间留一个空格即可。 (2认同)

DNR*_*DNR 24

试着这样做:

x = " {{ Hello }} {0} "
print x.format(42)
Run Code Online (Sandbox Code Playgroud)


paj*_*ton 22

试试这个:

x = "{{ Hello }} {0}"


Geo*_*lis 14

虽然没有更好,仅供参考,您也可以这样做:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
Run Code Online (Sandbox Code Playgroud)

例如,当有人想要打印时,它可能很有用{argument}.它可能比可读性更强'{{{}}}'.format('argument')

请注意,在Python 2.7之后省略了参数位置(例如,{}而不是{0})


ccp*_*zza 14

f 字符串 (python 3)

\n

您可以通过仅对要应用 f 魔法的字符串部分使用 f 字符串来避免必须使用双大括号,并对所有文字且可能包含 \'unsafe\ 的内容使用常规(哑)字符串' 特殊字符。让 python只需将多个字符串堆叠在一起即可完成字符串连接。

\n
number = 42\nprint("{The answer is} "  \nf"{number}" \n" {thanks for all the fish}")\n\n### OUTPUT:\n{The answer is} 42 {thanks for all the fish}\n
Run Code Online (Sandbox Code Playgroud)\n
\n

注意:字符串之间不需要换行。我添加它们只是为了便于阅读。您也可以将上面的代码写成如下所示:

\n

\xe2\x9a\xa0\xef\xb8\x8f 警告:这可能会伤害您的眼睛或让您头晕!

\n
print("{The answer is} "f"{number}"" {thanks for all the fish}")\n
Run Code Online (Sandbox Code Playgroud)\n
\n

  • 不鼓励隐式字符串连接。Guido 从 C 中复制了它,但在那里需要它的原因并不真正适用于 Python。- https://groups.google.com/g/python-ideas/c/jP1YtlyJqxs?pli=1 (3认同)

def*_*ant 12

key = "FOOBAR"
print(f"hello {{{key}}}")
Run Code Online (Sandbox Code Playgroud)

输出

hello {FOOBAR}
Run Code Online (Sandbox Code Playgroud)

如果有人想使用 fstring 在大括号内打印一些内容。


Ric*_*ard 9

如果需要在字符串中保留两个花括号,则变量的每一侧都需要 5 个花括号。

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
Run Code Online (Sandbox Code Playgroud)

  • 对于使用 f 字符串的用户,请在两侧使用 4 个花括号,而不是 5 个 (2认同)

tvt*_*173 5

如果你要做很多事情,最好定义一个实用函数,它可以让你使用任意的替代支撑,比如

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'
Run Code Online (Sandbox Code Playgroud)

请注意,这将使用括号为长度为2的字符串或两个字符串的可迭代(对于多字符分隔符).


小智 5

我最近遇到了这个问题,因为我想将字符串注入到预先格式化的 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
Run Code Online (Sandbox Code Playgroud)

然后你可以做类似的事情:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")
Run Code Online (Sandbox Code Playgroud)

如果性能不是问题,就可以完成工作。