如何在python字符串中打印文字大括号字符并在其上使用.format?
x = " \{ Hello \} {0} "
print x.format(42)
给我:{Hello} 42
我想打印输出:{Hello} 42
10个解决方案
1382 votes
你需要加倍{}和{{:
>>> x = " {{ Hello }} {0} "
>>> print x.format(42)
' { Hello } 42 '
以下是格式字符串语法的Python文档的相关部分:
格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中。 如果您需要在文字文本中包含大括号字符,则可以通过加倍来转义它:{{和}}。
Greg Hewgill answered 2018-12-17T04:59:05Z
55 votes
你通过加倍括号来逃避它。
例如:
x = "{{ Hello }} {0}"
print x.format(42)
Kamil Kisiel answered 2018-12-17T04:59:29Z
24 votes
试着这样做:
x = " {{ Hello }} {0} "
print x.format(42)
DNR answered 2018-12-17T04:59:48Z
21 votes
试试这个:
x = "{{ Hello }} {0}"
pajton answered 2018-12-17T05:00:12Z
21 votes
OP写了这样的评论:
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"}
在处理JSON时出现“逃避大括号”问题是很常见的。
我建议这样做:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
它比替代品更清洁,它是:
'{{"all": false, "selected": "{}"}}'.format(data)
当JSON字符串比示例更复杂时,使用json库肯定是更可取的。
twasbrillig answered 2018-12-17T05:00:49Z
14 votes
Python 3.6+(2017)
在最近的Python版本中,可以使用f-strings(另请参阅PEP498)。
使用f-strings,应该使用双{{或}}
n = 42
print(f" {{Hello}} {n} ")
产生所需的
{Hello} 42
如果您需要在括号中解析表达式而不是使用文字文本,则需要三组括号:
hello = "HELLO"
print(f"{{{hello.lower()}}}")
产生
{hello}
divenex answered 2018-12-17T05:01:31Z
10 votes
虽然没有更好,仅供参考,您也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
它可能是有用的,例如当有人想要打印{}.它可能比{0}更具可读性
请注意,在Python 2.7之后省略了参数位置(例如{}而不是{0})
George Aprilis answered 2018-12-17T05:02:00Z
5 votes
如果你要做很多事情,最好定义一个实用函数,它可以让你使用任意的替代支撑,比如
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的字符串或两个字符串的可迭代(对于多字符分隔符)。
tvt173 answered 2018-12-17T05:02:24Z
1 votes
原因是,%s的语法是.format()所以在你的情况下.format()无法识别{Hello}所以它抛出了一个错误。
您可以使用双花括号{{}}覆盖它,
x = " {{ Hello }} {0} "
要么
试试%s进行文本格式化,
x = " { Hello } %s"
print x%(42)
Mohideen ibn Mohammed answered 2018-12-17T05:02:57Z
-6 votes
如果必须在参数字典的键值或格式方法列表周围放置大括号,请尝试以下操作:
>>> "{o}Hello {a}{c}".format(**{"o":"{","c":"}","a":42})
'{Hello 42}'
acacia answered 2018-12-17T05:03:17Z