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

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

给我: Key Error: Hello\\\\ json

我要打印输出: {Hello} 42 函数


#1楼

尽管没有更好的效果,但仅供参考,您也能够这样作: spa

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

例如,当有人要打印{argument}时,它可能颇有用。 它可能比'{{{}}}'.format('argument')更具可读性 firefox

请注意,在Python 2.7以后,您省略了参数位置(例如,用{}代替{0}code


#2楼

OP写了这个评论: orm

我试图出于某种目的格式化小型JSON,例如: '{"all": false, "selected": "{}"}'.format(data)以获取相似{"all": false, "selected": "1,2"} 字符串

在处理JSON时常常会出现“转义括号”问题。 get

我建议这样作: cmd

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

它比替代方案更清洁,替代方案是: string

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

当JSON字符串比示例复杂时,最好使用json库。


#3楼

若是您打算作不少事情,最好定义一个实用函数,让您使用任意大括号替代项,例如

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的字符串或两个字符串为可迭代的字符串(对于多字符定界符)。


#4楼

缘由是{}.format()的语法,所以在您的状况下.format()没法识别{Hello}所以引起了错误。

您能够使用双大括号{{}}覆盖它,

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

要么

尝试使用%s进行文本格式设置,

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

#5楼

Python 3.6+(2017年)

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

对于f字符串,应该使用双{{}}

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

产生所需的

{Hello} 42

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

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

产生

{hello}
相关文章
相关标签/搜索