0

I need to automatize the writing of a latex file. To do this, I need to format a string already containing "{" and "}" characters. To make an example, consider the string

a = "\begin{theorem} Consider the integral $$ \int_a^b {}dx  $$bla bla bla. \end{theorem}"
functions = ["x^2 -2", "e^{-x} + 7"]
f = functions[1]
a.format(f)

This code gives an error since there are already parenthesis "{}" filled with the word "theorem" in the beginning. If I erase "\begin{theorem}" and "\end{theorem}" the code works.

How can I format the string already containing the substring "{something}"?

I am using python 3.8, anaconda and spyder.

I could split the string in two, or three; or I could consider the word "theorem" as an argument of the format method, but can I do it directly? in other words which is the fastest solution?

skywalker
  • 21
  • 2
  • Does this answer your question? [How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?](https://stackoverflow.com/questions/5466451/how-do-i-escape-curly-brace-characters-in-a-string-while-using-format-or) – slothrop Jun 26 '23 at 20:21
  • Also, `\b` is interpreted as a backspace. You can fix this with double-backslash (`a = "\\begin... "`) or using a raw string literal (`a = r"\begin... "`) – slothrop Jun 26 '23 at 20:23
  • Right. I think I wrote "\\begin..." but the editor changed it into "\begin..". – skywalker Jun 26 '23 at 20:25

2 Answers2

2

Doubling the curly brackets ({{ and }}) tells Python "these curly brackets aren't for formatting":

a = "\begin{{theorem}} Consider the integral $$ \int_a^b {}dx  $$bla bla bla. \end{{theorem}}"

This works with a.format(f) now.

Addison
  • 53
  • 6
-1

Consider the Following code

a = "\\begin{func1} Consider the integral $$ \int_a^b {func2}dx  $$bla bla bla. \end{func1}"
functions = ["x^2 -2", "e^{-x} + 7"]
f1 ,f2 = functions
a = a.format(func1=f1 ,func2=f2)

I have added a backslash for string "a" so that "b" at the beginning of the string will not be discarded. Guess it helps!

debrian
  • 9
  • 3