Python:带有自定义分隔符的格式字符串 [英] Python: format string with custom delimiters

查看:347
本文介绍了Python:带有自定义分隔符的格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想解析一个字符串并替换一些标签,这是字典的关键。



编辑这个字符串已经包含大括号,我不能改变它们。

我想我可以把大括号内的键放在字符串中,然后使用:

  output = input.format(** dictionary) 

但它给我 KeyError 字符串已经包含大括号:

  input =
DATABASE = {
'name': '{DB_NAME}'
}

有没有办法改变默认的 .format 替换标识符?



我应该使用像猎豹这样的高级解析器吗?

编辑

这不是为我需要保留大括号,并为 .format 使用不同的分隔符。



所以,答案你不想被替换的花括号加倍并不适合我的问题。

我认为可以使用替代分隔符。您需要使用双花括号 {{ }} 来替换您不想被替换的大括号由 format()
$ b

  inp =
DATABASE = {{
'name':'{DB_NAME}'
}}

dictionary = {'DB_NAME':'abc'}
输出= inp.format(**字典)
print(输出)

输出

  DATABASE = {
'name':'abc'
}


I want to parse a string and replace some tags, which are the keys of a dictionary.

EDIT The string already contains curly brackets and I cannot change them.

I thought I could place keys within curly brackets in the string and then use:

output = input.format(**dictionary)

But it gives me KeyError because the input string already contains curly brackets:

input = """
DATABASE = {
    'name': '{DB_NAME}'
}"""

Is there a way to change default .format replacement identifiers?

Should I use high-level parsers like cheetah?

EDIT

This is not a duplicate of How can I print literal curly-brace characters in python string and also use .format on it? as I need to keep curly brackets just as they are and use a different delimiter for .format.

So, the answer "double the curly brackets that you don't want to be replaced" doesn't fit my question.

解决方案

I don't think it is possible to use alternative delimiters. You need to use double-curly braces {{ }} for curly braces that you don't want to be replaced by format():

inp = """
DATABASE = {{
    'name': '{DB_NAME}'
}}"""

dictionary = {'DB_NAME': 'abc'}
output = inp.format(**dictionary)
print(output)

Output

DATABASE = {
    'name': 'abc'
}

这篇关于Python:带有自定义分隔符的格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆