如何在python字符串中打印文字大括号字符并在其上使用.format?

问题:如何在python字符串中打印文字大括号字符并在其上使用.format?

x = " \{ Hello \} {0} "
print(x.format(42))

给我 : Key Error: Hello\\

我想打印输出: {Hello} 42

x = " \{ Hello \} {0} "
print(x.format(42))

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42


回答 0

您需要将{{和加倍}}

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

这是Python文档中有关格式字符串语法的相关部分:

格式字符串包含用花括号括起来的“替换字段” {}。花括号中不包含的所有内容均视为文字文本,该文本原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和来对其进行转义}}

You need to double the {{ and }}:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

Here’s the relevant part of the Python documentation for format string syntax:

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 }}.


回答 1

您可以通过将花括号加倍来逃脱它。

例如:

x = "{{ Hello }} {0}"
print(x.format(42))

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print(x.format(42))

回答 2

Python 3.6+(2017年)

在最新版本的Python中,将使用f字符串(另请参阅PEP498)。

对于f弦,应使用double {{}}

n = 42  
print(f" {{Hello}} {n} ")

产生所需的

 {Hello} 42

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

hello = "HELLO"
print(f"{{{hello.lower()}}}")

产生

{hello}

Python 3.6+ (2017)

In the recent versions of Python one would use f-strings (see also PEP498).

With f-strings one should use double {{ or }}

n = 42  
print(f" {{Hello}} {n} ")

produces the desired

 {Hello} 42

If you need to resolve an expression in the brackets instead of using literal text you’ll need three sets of brackets:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

produces

{hello}

回答 3

OP写了这个评论:

我正在尝试出于某种目的格式化小型JSON,例如:'{"all": false, "selected": "{}"}'.format(data)获得类似{"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字符串比示例复杂时,最好使用该库。

The OP wrote this comment:

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.

I suggest doing this:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)

It’s cleaner than the alternative, which is:

'{{"all": false, "selected": "{}"}}'.format(data)

Using the json library is definitely preferable when the JSON string gets more complicated than the example.


回答 4

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(42)

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)

回答 5

尝试这个:

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

Try this:

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


回答 6

尽管没有更好的效果,但仅供参考,您也可以这样做:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

例如,当有人要打印时,此功能很有用{argument}。它可能比'{{{}}}'.format('argument')

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

Although not any better, just for the reference, you can also do this:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

It can be useful for example when someone wants to print {argument}. It is maybe more readable than '{{{}}}'.format('argument')

Note that you omit argument positions (e.g. {} instead of {0}) after Python 2.7


回答 7

如果您打算做很多事情,最好定义一个实用函数,让您使用任意大括号替代项,例如

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}'

请注意,这将适用于括号为长度为2的字符串或两个字符串为可迭代的字符串(对于多字符定界符)。

If you are going to be doing this a lot, it might be good to define a utility function that will let you use arbitrary brace substitutes instead, like

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}'

Note that this will work either with brackets being a string of length 2 or an iterable of two strings (for multi-character delimiters).


回答 8

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

如果性能不成问题,则完成工作。

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

You can then do something like:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

Gets the job done if performance is not an issue.


回答 9

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

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

If you need to keep two curly braces in the string, you need 5 curly braces on each side of the variable.

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

回答 10

原因是,{}.format()您的情况下的语法,因此.format()无法识别,{Hello}因此引发了错误。

您可以使用双大括号{{}}覆盖它,

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

要么

尝试%s格式化文本,

x = " { Hello } %s"
print x%(42)  

Reason is , {} is the syntax of .format() so in your case .format() doesn’t recognize {Hello} so it threw an error.

you can override it by using double curly braces {{}},

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

or

try %s for text formatting,

x = " { Hello } %s"
print x%(42)  

回答 11

我在尝试打印文本时偶然发现了这个问题,可以将其复制粘贴到Latex文档中。我扩展这个答案,并使用命名的替换字段:

假设您要打印出带有诸如的索引的多个变量的乘积 ,在Latex中将是$A_{ 0042 }*A_{ 3141 }*A_{ 2718 }*A_{ 0042 }$ 这样的代码。以下代码使用命名字段完成工作,因此对于许多索引而言,它仍然可读:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

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:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

回答 12

如果你想打印一个大括号(例如{),您可以使用{{,如果你愿意,你可以在后面的字符串添加多个支架。例如:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

If you want to only print one curly brace (for example {) you can use {{, and you can add more braces later in the string if you want. For example:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

回答 13

当您只是想插入代码字符串时,我建议您使用jinja2,它是Python的全功能模板引擎,即:

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))

因此,您不会因为其他答案而被迫复制花括号

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}')

You can do this by using raw string method by simply adding character ‘r’ without quotes before the string.

# to print '{I am inside braces}'
print(r'{I am inside braces}')