在使用.format时,如何在字符串中逃脱字符串中的Curly-Brace({})字符?

发布于 2025-01-30 04:40:05 字数 167 浏览 4 评论 0原文

非工作示例:

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

所需的输出:

 {Hello} 42 

Non-working example:

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

Desired output:

 {Hello} 42 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

木有鱼丸 2025-02-06 04:40:05

您需要将{{}}}}加倍,

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

这是格式字符串语法的python文档

格式字符串包含卷曲括号包围的“替换字段” {}。牙套中未包含的任何内容都被认为是字面文本,该文本被复制到输出不变。如果您需要在文字文本中包含撑杆字符,则可以通过加倍来逃脱:{{ and }}}

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

憧憬巴黎街头的黎明 2025-02-06 04:40:05

python 3.6+(2017)

在最新版本的Python中,将使用 f-strings (另请参见

使用f-strings,应该使用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}
陈甜 2025-02-06 04:40:05

您可以将牙套加倍逃脱它。

例如:

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

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print(x.format(42))
萌逼全场 2025-02-06 04:40:05

您想用字符{}格式化字符串,

您只需将它们加倍即可。

格式{带有f'{{' and }带有f'}}'

so:

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')

输出:输出:

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

或确切的示例:

number = 42
print(f'{{Hello}} {number}')

将打印:

{Hello} 42

最后:

number = 42
string = "bob"
print(f'{{Hello}} {{{number}}} {number} {{{string}}} {string} ')

{hello} {42} 42 {bob} bob

You want to format a string with the character { or }

You just have to double them.

format { with f'{{' and }with f'}}'

So :

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')

Output :

Hello bob ! I want to print } and { or { }

OR for the exact example :

number = 42
print(f'{{Hello}} {number}')

Will print :

{Hello} 42

Finally :

number = 42
string = "bob"
print(f'{{Hello}} {{{number}}} {number} {{{string}}} {string} ')

{Hello} {42} 42 {bob} bob

终止放荡 2025-02-06 04:40:05

OP写下了此评论:

我试图为某些目的格式化一个小JSON类似{“ 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.

笛声青案梦长安 2025-02-06 04:40:05

尝试以下方法:

x =“ {{hello}} {0}”

Try this:

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

清醇 2025-02-06 04:40:05

尝试这样做:

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

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)
孤檠 2025-02-06 04:40:05

尽管没有任何更好的方法,但您也可以做到这一点:

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

例如,当某人想要打印{groment}时,它可能很有用。它可能比'{{{{}}}'。格式('参数')

请注意,您省略参数位置(例如{}而不是),它可能比'{{{} }}'。 {0})python 2.7

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

虚拟世界 2025-02-06 04:40:05
key = "FOOBAR"
print(f"hello {{{key}}}")

输出

hello {FOOBAR}

如果有人想使用FSTRINGS在卷曲括号内打印一些东西。

key = "FOOBAR"
print(f"hello {{{key}}}")

outputs

hello {FOOBAR}

In case someone wanted to print something inside curly brackets using fstrings.

走野 2025-02-06 04:40:05

f-string(Python 3)

您可以避免必须通过使用F-Sning 仅使用F-strings 将卷曲支架加倍应用,并使用常规(哑巴)字符串作为字面意义上的所有内容,并且可能包含“不安全”的特殊字符。 让python让您简单地通过 by 将多个字符串堆叠在一起。

number = 42
print("{The answer is} "  
f"{number}" 
" {thanks for all the fish}")

### OUTPUT:
{The answer is} 42 {thanks for all the fish}

注意:字符串之间的线断裂为可选。我只添加了它们以使其可读性。您还可以编写上面的代码,如下所示:

⚠️警告:这可能会伤害您的眼睛或让您头晕!

  print(“ {答案是}” f“ {number}”“ {谢谢所有的鱼}”)
 

f-strings (python 3)

You can avoid having to double the curly brackets by using f-strings ONLY for the parts of the string where you want the f-magic to apply, and use regular (dumb) strings for everything that is literal and might contain 'unsafe' special characters. Let python do the string joining for you simply by stacking multiple strings together.

number = 42
print("{The answer is} "  
f"{number}" 
" {thanks for all the fish}")

### OUTPUT:
{The answer is} 42 {thanks for all the fish}

NOTE: Line breaks between the strings are optional. I have only added them for readability. You could as well write the code above as shown below:

⚠️ WARNING: This might hurt your eyes or make you dizzy!

print("{The answer is} "f"{number}"" {thanks for all the fish}")
久而酒知 2025-02-06 04:40:05

如果您需要将两个卷发括号放在字符串中,则需要在变量的每一侧进行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}}'
青芜 2025-02-06 04:40:05

如果您要进行很多操作,那么定义一个实用程序功能可能会很好地使用任意的支撑式替代品,例如

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的括号为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).

不念旧人 2025-02-06 04:40:05

我最近遇到了这一点,因为我想将字符串注入预制的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.

极致的悲 2025-02-06 04:40:05

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

您可以使用Double Curly Braces {{}}

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)  
倾其所爱 2025-02-06 04:40:05

我参加这个聚会迟到了。我成功地将括号放在替换元素中,这样的是:

print('{0} {1}'.format('{hello}', '{world}'))

严格来说

{hello} {world}

,这不是OP要求的,因为他/他想要格式字符串的括号,但这可能会对某人有所帮助。

I am ridiculously late to this party. I am having success placing the brackets in the replacement element, like this:

print('{0} {1}'.format('{hello}', '{world}'))

which prints

{hello} {world}

Strictly speaking this is not what OP is asking, as s/he wants the braces in the format string, but this may help someone.

荒路情人 2025-02-06 04:40:05

这是另一个解决方案。为什么很棒:

  1. 让您最初保持卷发括号。
  2. 如果找不到变量,则没有例外。

只是这个简单的功能:

def format_string_safe(text:str, **kwargs):
    if text is None:
        return ''
    result = text
    try:    
        for k in kwargs:
            result = result.replace(f'{{{k}}}', str(kwargs[k]))
        return result
    except Exception as ex:
        print_traceback(ex)
    return text

如何使用:

format_string_safe('THis is my text with some {vars}.', vars=22)

Here is another solution for it. Why it's great:

  1. Allows you to keep the curly brackets originally single.
  2. No exceptions if a variable is not found.

It's just this simple function:

def format_string_safe(text:str, **kwargs):
    if text is None:
        return ''
    result = text
    try:    
        for k in kwargs:
            result = result.replace(f'{{{k}}}', str(kwargs[k]))
        return result
    except Exception as ex:
        print_traceback(ex)
    return text

How to use:

format_string_safe('THis is my text with some {vars}.', vars=22)
怪我闹别瞎闹 2025-02-06 04:40:05

我使用double {{{}}来防止FSTRING值注入,

例如,Heres My Postgres Update语句以更新一个整数数组列,该列以{}的表达式捕获数组,即:

ports ='{100,200,300}'

带FSTRINGS '它的

ports = [1,2,3]

query = f"""
   UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""

实际查询语句将

UPDATE table SET ports = '{1,2,3}'

是一个有效的Postgres Satement

I used a double {{ }} to prevent fstring value injection,

for example, heres my Postgres UPDATE statement to update a integer array column that takes expression of {} to capture the array, ie:

ports = '{100,200,300}'

with fstrings its,

ports = [1,2,3]

query = f"""
   UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""

the actual query statement will be,

UPDATE table SET ports = '{1,2,3}'

which is a valid postgres satement

再可℃爱ぅ一点好了 2025-02-06 04:40:05

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

您想打印出带有Mulitple变量的产品,索引,例如
,在乳胶中为$ a_ {0042}*a_ {3141}*a_ {2718}*a_ 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
enter image description here, 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))
妄司 2025-02-06 04:40:05

您可以使用“报价墙”将格式的字符串部分与常规字符串部分分开。

从:

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

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

一个更清晰的示例将

string = 10
print(f"{string} {word}")

输出:

NameError: name 'word' is not defined

现在,添加报价墙,如:

string = 10
print(f"{string}"" {word}")

输出:

10 {word}

You can use a "quote wall" to separate the formatted string part from the regular string part.

From:

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

to

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

A clearer example would be

string = 10
print(f"{string} {word}")

Output:

NameError: name 'word' is not defined

Now, add the quote wall like so:

string = 10
print(f"{string}"" {word}")

Output:

10 {word}
々眼睛长脚气 2025-02-06 04:40:05

如果您只想打印卷发的一侧:

a=3
print(f'{"{"}{a}')
>>> {3

If you want to print just one side of the curly brace:

a=3
print(f'{"{"}{a}')
>>> {3
七七 2025-02-06 04:40:05

如果要打印一个卷曲括号(例如{),则可以使用{{,并且可以在以后在如果需要,字符串。
例如:

>>> 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'
相思碎 2025-02-06 04:40:05

当您只是想插值代码字符串时,我建议使用 jinja2 这是一个完整的 - 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))

您不会被强制重复卷曲牙套,因为所有其他答案都建议

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

深府石板幽径 2025-02-06 04:40:05

如果您需要可以格式格式的F弦模板中的卷曲支架,则需要在F-string的一组卷曲支架中输出一个包含两个卷发括号的字符串:

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'

If you need curly braces within a f-string template that can be formatted, you need to output a string containing two curly braces within a set of curly braces for the f-string:

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'
丢了幸福的猪 2025-02-06 04:40:05

还是仅参数括号本身?可能很冗长。

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}

Or just parametrize the bracket itself? Probably very verbose.

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文