社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

pkaramol • 4 年前 • 1249 次点击  
x = " \{ Hello \} {0} "
print(x.format(42))

给我: Key Error: Hello\\

{Hello} 42

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/53719
 
1249 次点击  
文章 [ 14 ]  |  最新文章 4 年前
Harsh Aggarwal
Reply   •   1 楼
Harsh Aggarwal    4 年前

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

# to print '{I am inside braces}'
print(r'{I am inside braces}')
dreftymac
Reply   •   2 楼
dreftymac    4 年前

使用自定义占位符标记 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)
#;;

另见

Mohideen bin Mohammed
Reply   •   3 楼
Mohideen bin Mohammed    6 年前

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

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

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

尝试 %s

x = " { Hello } %s"
print x%(42)  
v.tralala
Reply   •   4 楼
v.tralala    4 年前

我在尝试打印文本时偶然发现了这个问题,我可以将其复制粘贴到乳胶文档中。我继续 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))
Kristján Valur
Reply   •   5 楼
Kristján Valur    4 年前

我最近遇到这个问题,因为我想将字符串注入预格式化的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")

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

Richard
Reply   •   6 楼
Richard    4 年前

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

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
tvt173
Reply   •   7 楼
tvt173    7 年前

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

George Aprilis
Reply   •   8 楼
George Aprilis    8 年前

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

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

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

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

pajton
Reply   •   9 楼
pajton    13 年前

试试这个:

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

DNR
Reply   •   10 楼
DNR    13 年前

x = " {{ Hello }} {0} "
print x.format(42)
Bryan Bryce divenex
Reply   •   11 楼
Bryan Bryce divenex    5 年前

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

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

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

 {Hello} 42

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

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

生产

{hello}
Nick T twasbrillig
Reply   •   12 楼
Nick T twasbrillig    4 年前

评论写道:

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

Boris Kamil Kisiel
Reply   •   13 楼
Boris Kamil Kisiel    4 年前

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

x = "{{ Hello }} {0}"
print(x.format(42))
Boris Kamil Kisiel
Reply   •   14 楼
Boris Kamil Kisiel    4 年前

你需要加倍 {{ }}

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

以下是 Python documentation for format string syntax :

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