1

I have the following codes as my figure title:

params_text = r'$\epsilon_1={{{:d}}}, \epsilon_2={{{:d}}}, S_1=10^{{{:d}}}, S_2=10^{{{:d}}}, $'.format(eps1,eps2,int(np.log10(S1)),int(np.log10(S2)))

fig.suptitle('(Tom, 2021) FIG.7: \n'+params_text)

In my figure, I want (Tom,2021) FIG.7: in the first line of the title and the list of parameters in the second line. The above codes do what I want to do and I'm happy about that.

My question is: how can I break up params_text in my codes for better readability (I will add a lot more parameters and having everything on one line can be hard to read) without affecting the actual figure title? Normally I can use \ to break up my normal codes to multiple lines, but what if I want to break up that long string variable?

Physicist
  • 2,848
  • 8
  • 33
  • 62
  • Is there something specific to the content of the string that I'm overlooking, or are you just asking about [how to create a multiline string?](https://stackoverflow.com/questions/10660435/pythonic-way-to-create-a-long-multi-line-string) – Brian61354270 Oct 13 '20 at 22:10
  • @Brian I essentially just want to create a multiline string (in my code editor for display but not the actual output), but I'm not sure how to do it when the string have the `.format(...)` placeholder formatting and latex symbols. – Physicist Oct 13 '20 at 22:12
  • Have you tried any of the standard techniques discussed in that question? Bear in mind that string literal concatenation happens at compile time, so `"{}" " test".format(...)` is the same as `"{} test".format(...)`. I don't believe the formatting placeholders or the fact that the string contains LaTeX are consequential. – Brian61354270 Oct 13 '20 at 22:15
  • What do you think of [my answer below](https://stackoverflow.com/a/64353666/2749397)? Is it useful? Is it exactly what you want? – gboffi Oct 19 '20 at 12:27

1 Answers1

1

Imho to format LaTeX code the old style formatting is better, as you have not to quote the omnipresent curly brackets ፨ that said, you can define the format string on one (shorter) line and format the data in a second (shorter) line

fmt = r'$\epsilon_1={%d}, \epsilon_2={%d}, S_1=10^{%d}, S_2=10^{%d}, $'
params_text = fmt%(eps1,eps2,int(np.log10(S1)),int(np.log10(S2)))

If the format string becomes REALLY long, a simple&nice way to split it across lines could be

fmt = (r'$\epsilon_1={%d}, '
         '\epsilon_2={%d}, '
         'S_1=10^{%d}, '
         'S_2=10^{%d}, $')

To show that the technique above is working, from the REPL

>>> a = (r'aaaa'
...       '\\\\')
>>> a
'aaaa\\\\'

NB: you have 4 back slashes in the string a.

A similar technique can be used also to produce the formatted string

params_text = fmt%( x1,
                    x2,
                    ...,
                    xn)
gboffi
  • 22,939
  • 8
  • 54
  • 85