In Python 3.6, there is the new f-string to include variables in strings which is great, but how do you correctly apply these strings to get super or subscripts printed for matplotlib?
(to actually see the result with the subscript, you need to draw the variable foo
on a matplotlib plot)
In other words how do I get this behaviour:
var = 123
foo = r'text$_{%s}$' % var
text<sub>123</sub>
Using the new f-string syntax? So far, I have tried using a raw-string literal combined with an f-string, but this only seems to apply the subscript to the first character of the variable:
var = 123
foo = fr'text$_{var}$'
text<sub>1</sub>23
Because the {
has an ambiguous function as delimiting what r
should consider subscript and what f
delimits as a place for the variable.
Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String.
f-strings in Python don't use __str__ or __repr__ . They use __format__ . So to get the same result as f'{Thing. A}' , you'd need to call format(Thing.
Calling functions with f-stringPython f-strings enables us to call functions within it. Thus, optimizing the code to an extent. The same way can be used for creating lambda functions within f-string bracets.
You need to escape the curly brackets by doubling them up, and then add in one more to use in the LaTeX formula. This gives:
foo = f'text$_{{{var}}}$'
Example:
plt.figure()
plt.plot([1,2,3], [3,4,5])
var = 123
plt.text(1, 4,f'text$_{{{var}}}$')
Output:
Incidentally, in this example, you don't actually need to use a raw-string literal.
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