Home > Back-end >  String formating and Tex rendering
String formating and Tex rendering

Time:11-30

I am running into some issues getting things to display correctly when combining string formating and tex rendering in python. I want to index a series of energy levels by integers. This works fine for single-digit integers, however when I try for example:

s = r"$E_{}$".format(10)

the result looks like E10 while I want it to look like E10. I have tried using double braces but this doesn't seem to work since

s = r"$E_{{}}$".format(10)

results in "E" without any subscript at all, and something like

s = r"$E_{{k}}$".format(k = 10)

predictably gives Ek.

To me it seems the problem here is that both the string formatting and Tex syntax make use of curly braces, and while doubling the braces does escape the formatting, this will not work for me, since I still want to insert the value of k somehow. Is there any way around this issue, or will I have to resort to the old school method of formatting strings?

CodePudding user response:

Literal { can be included with {{ - and then you need another {} to get the formatting placeholder - so you need 3:

s = r"$E_{{{}}}$".format(10)
print(s)

Results in:

$E_{10}$

Which should be rendered into what you wanted.

  • Related