Python – How to Format String with Extra Curly Braces

escapingpythonpython-3.xstring-formatting

I have a LaTeX file I want to read in with Python 3 and format a value into the resultant string. Something like:

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

But I have not been able to figure out how to do this since the new way of doing string formatting uses {val} notation and since it is a LaTeX document, there are tons of extra {} characters.

I've tried something like:

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

but I get

KeyError: 'This and that'

Best Answer

Method 1, which is what I'd actually do: use a string.Template instead.

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

Method 2: add extra braces. Could do this using a regexp.

>>> 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}'

(possible) Method 3: use a custom string.Formatter. I haven't had cause to do this myself so I don't know enough of the details to be helpful.

Related Question