Python - 使用乳胶格式化中断字符串

时间:2014-05-09 21:04:09

标签: python string matplotlib latex

我有一个方程式,我需要在一个情节中显示。等式的公式很长,所以我想把它分成不超过80个字符的单行。

这是MWE:

import matplotlib.pyplot as plt

num = 25

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) - |B_t - f_h+f_g)|}{B}$") % num

fig = plt.figure()
ax = fig.add_subplot(111)

plt.scatter([0., 1.], [0., 1.])
plt.text(0.5, 0.5, text, transform=ax.transAxes)

plt.show()

如果我这样写它就会创建没有问题的情节,但是当我试图打破text行时,我会遇到各种错误。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

一个简单的可能性就是使用连接:

text = (r"$RE_{%d}$ = $\frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) " +
        r" - |B_t - f_h+f_g)|}{B}$") % num

你也可以使用三引号多线字符串,但是你需要手动替换换行符:

def lf2space(s):
  return " ".join(s.split("\n"))

text = lf2space(r"""
    $RE_{%d} = 
       \frac{\left(\sum^{l_k}{q_m} -\sum^{n}{f_h}\right) 
                - |B_t - f_h+f_g)|}
            {B}$
  """ % num)
相关问题