【问题标题】:Format a string that has extra curly braces in it格式化一个包含额外花括号的字符串
【发布时间】:2012-02-06 14:10:27
【问题描述】:

我有一个 LaTeX 文件,我想用 Python 3 读取并将一个值格式化为结果字符串。比如:

...
\textbf{REPLACE VALUE HERE}
...

但我无法弄清楚如何做到这一点,因为进行字符串格式化的新方法使用 {val} 表示法,并且由于它是一个 LaTeX 文档,因此有大量额外的 {} 字符。

我尝试过类似的方法:

'\textbf{This and that} plus \textbf{{val}}'.format(val='6')

但我明白了

KeyError: 'This and that'

【问题讨论】:

    标签: python escaping python-3.x string-formatting


    【解决方案1】:

    方法 1,这就是我实际要做的:改用 string.Template

    >>> from string import Template
    >>> Template(r'\textbf{This and that} plus \textbf{$val}').substitute(val='6')
    '\\textbf{This and that} plus \\textbf{6}'
    

    方法2:添加额外的大括号。可以使用正则表达式来做到这一点。

    >>> r'\textbf{This and that} plus \textbf{val}'.format(val='6')
    Traceback (most recent call last):
      File "<interactive input>", line 1, in <module>
    KeyError: 'This and that'
    >>> r'\textbf{{This and that}} plus \textbf{{{val}}}'.format(val='6')
    '\\textbf{This and that} plus \\textbf{6}'
    

    (可能)方法3:使用自定义的string.Formatter。我自己没有理由这样做,所以我不知道足够的细节来提供帮助。

    【讨论】:

    • 是否有任何线索 string.Template 将来是否会被弃用?新的 python 3 {} 格式似乎包括这一点。但是,对于 LaTeX 编辑来说,模板要方便得多。
    • @levesque:嗯,从(待定)3.4 开始,它还没有被弃用,它提供的功能与 {} 格式化本身不同,所以我认为它会持续一段时间。
    • 添加额外大括号而不是使用正则表达式可能更好的方法是使用str.translateunformatter = str.maketrans({'{': '{{', '}': '}}'}),然后修复给定的字符串,goodstring = badstring.translate(unformatter)(注意:问题是关于 Python 3.x;在 2.x 上,这仅适用于 unicode,不适用于 str,因为只有 unicode支持 1-n 翻译映射。)
    猜你喜欢
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-29
    • 2015-10-01
    相关资源
    最近更新 更多