Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a string that has extra curly braces in it

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'
like image 433
Keith Pinson Avatar asked Feb 06 '12 14:02

Keith Pinson


People also ask

How do you escape curly braces in string format?

Format strings contain “replacement fields” surrounded by curly braces {} . Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }} .

How do you use curly braces in string format?

To escape curly braces and interpolate a string inside the String. format() method use triple curly braces {{{ }}} . Similarly, you can also use the c# string interpolation feature instead of String.

What does {} format do in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}.


1 Answers

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.

like image 133
DSM Avatar answered Sep 22 '22 20:09

DSM