代码之家  ›  专栏  ›  技术社区  ›  pkaramol

python:无法格式化类似json的字符串[duplicate]

  •  0
  • pkaramol  · 技术社区  · 6 年前
    x = " \{ Hello \} {0} "
    print(x.format(42))
    

    给我: Key Error: Hello\\

    {Hello} 42

    0 回复  |  直到 6 年前
        1
  •  1872
  •   Boris Verkhovskiy Brian Clapper    6 年前

    你需要加倍 {{ }}

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

    以下是 Python documentation for format string syntax :

    格式字符串包含由大括号包围的替换字段 {} . 任何不包含在大括号中的内容都被视为文字文本,它将原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍来对其进行转义: }}

        2
  •  66
  •   Boris Verkhovskiy Brian Clapper    6 年前

    你可以通过把牙套加倍来逃避。

    x = "{{ Hello }} {0}"
    print(x.format(42))
    
        3
  •  42
  •   Nick T twasbrillig    6 年前

    评论写道:

    我正试图格式化一个小的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字符串变得比示例更复杂时,库无疑更可取。

        4
  •  40
  •   Bryan Bryce divenex    7 年前

    在最近的Python版本中 f-strings PEP498 ).

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

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

     {Hello} 42
    

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

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

    生产

    {hello}
    
        5
  •  23
  •   DNR    14 年前

    x = " {{ Hello }} {0} "
    print x.format(42)
    
        6
  •  21
  •   pajton    14 年前

    试试这个:

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

        7
  •  13
  •   George Aprilis    10 年前

    虽然不是更好,但仅供参考,您也可以这样做:

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

    {argument} . 它可能比 '{{{}}}'.format('argument')

    注意,您省略了参数位置(例如。 {} {0} )在Python2.7之后

        8
  •  4
  •   tvt173    9 年前

    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的iterable的两个字符串(用于多字符分隔符)。

        9
  •  1
  •   Richard    6 年前

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

    >>> myvar = 'test'
    >>> "{{{{{0}}}}}".format(myvar)
    '{{test}}'
    
        10
  •  1
  •   Kristján Valur    6 年前

    我最近遇到这个问题,因为我想将字符串注入预格式化的JSON。 我的解决方案是创建一个helper方法,如下所示:

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

    如果性能不是问题,则完成任务。

        11
  •  1
  •   v.tralala    6 年前

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

    假设您要打印多个变量的乘积,这些变量的索引如下 enter image description here ,在乳胶中 $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))
    
        12
  •  0
  •   Mohideen bin Mohammed    8 年前

    原因是, {} 是的语法 .format() 所以对你来说 不认识 {Hello}

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

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

    尝试 %s

    x = " { Hello } %s"
    print x%(42)  
    
        13
  •  0
  •   dreftymac    6 年前

    使用自定义占位符标记 Jinja2

    上下文

    • 巨蟒3.x
    • 替代品 string.format()
    • 这种方法使用 金贾2 为了提高性能的灵活性和额外的Python依赖性

    我们希望在python中使用自定义占位符分隔符 str.format()

    • string.format() 功能强大,但不支持占位符分隔符修改。
    • string.format() Delimiter collision
    • string.format() 默认的解决方法是将分隔符加倍。 这可能会很麻烦,因为它需要更改原始源代码,而更改默认占位符分隔符可能更直接。

    解决方案

    金贾2 作为python的替代 str.格式()

    • 将jinja2作为附加依赖项导入
    • 用一个定制类包装jinja2,使sytnax与
    • 允许其他增强功能,如自定义函数和筛选器

    优势

    缺点

    • 内置python的性能更低 str.format
    • Jinja2有着与纯python不同的调试经验

    示例:基于自定义Jinja2的演示使用 可供替代的

    • 我们写了一个习惯 TPLjinja 使Jinja更像python的类
    # import custom class
    import TPLjinja
    import textwrap
    #;;
    
    # prepare source data
    ddmydata = dict()
    ddmydata['fname'] = 'Huomer'
    ddmydata['lname'] = 'Huimpson'
    ddmydata['motto'] = 'I love donuts!'
    #;;
    
    # prepare template
    sgtemplate = textwrap.dedent('''\
    Hello @{fname} @{lname}!
    We love your motto: ```@{motto}``` and we agree with you!
    ''')
    #;;
    
    # show output
    vout = TPLjinja(template=sgtemplate,delimiter="@",wrap="{").format(**ddmydata)
    print(vout)
    #;;
    
    # show how easy it is to change the delimiter syntax
    # vout = TPLjinja(template='''Hello $<fname> !''',delimiter="$",wrap="<").format(**ddmydata)
    # vout = TPLjinja(template='''Hello ~(fname) !''',delimiter="~",wrap="(").format(**ddmydata)
    # vout = TPLjinja(template='''Hello &<%fname%> !''',delimiter="&",wrap="<%").format(**ddmydata)
    #;;
    

    另见

        14
  •  -3
  •   Chetan Goyal    6 年前

    您可以使用raw string方法,只需在字符串前添加不带引号的字符“r”。

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