How can I print literal curly-brace characters in

2018-12-31 02:21发布

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

gives me : Key Error: Hello\\

I want to print the output: {Hello} 42

9条回答
墨雨无痕
2楼-- · 2018-12-31 02:36

Try doing this:

x = " {{ Hello }} {0} "
print x.format(42)
查看更多
时光乱了年华
3楼-- · 2018-12-31 02:40

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}
查看更多
君临天下
4楼-- · 2018-12-31 02:41

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

查看更多
像晚风撩人
5楼-- · 2018-12-31 02:41

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)  
查看更多
春风洒进眼中
6楼-- · 2018-12-31 02:43

You escape it by doubling the braces.

Eg:

x = "{{ Hello }} {0}"
print x.format(42)
查看更多
荒废的爱情
7楼-- · 2018-12-31 02:50

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.

查看更多
登录 后发表回答