How do I combine format strings with curly braces in subscript for axis labels?

Viewed 272

I am trying to use string formatting to insert subscript numbers in axis labels.

I have tried $_{}$, however it only works for numbers from 1-9, not for numbers with more than one digit. e.g., 13 becomes subscript 1 and normal 3:

enter image description here

I know that I must use _{13} to have all digits as subscript, but I did not manage to combine this with the {} syntax for string formatting.

  • I have tried $_{{}}$ but this just removes all values.

  • I have tried ''$_{'{}'}$ which also does not work.

This is my current code:

cclib.parser.ccopen('{}'.format(args["input"])).parse() 
axlabels = ["M"] 
for x in range(OmFragDim - 1): 
    label = 'L{}'.format(x + 1) 
    axlabels.append(label)

    ax.set_title('{}$_{}$, {:1.2f} nm'.format(ExS[args["state"] - 1][0], args["state"], stateE), loc='center', y=1.2)

How can I do this properly?

1 Answers

In the end you want to generate a string containing "$S_{13}$" so that it can be rendered by Matplotlib as a simple LaTeX snippet.

To achieve this you could use "${}_{{{}}}$".format("S", 13).

Explanation:

  • .format will replace any {} with each of the arguments.
  • Inside a .format string you have to use {{ to escape { and }} to escape } in the output string. This is because otherwise there would be parsing ambiguities.
Related