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'
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 }} .
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.
The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With