【问题标题】:Python combining the format method with long strings that use LaTeXPython 将格式方法与使用 LaTeX 的长字符串相结合
【发布时间】:2014-09-10 14:08:46
【问题描述】:

我正在尝试将包含多个 LaTeX 命令和变量的长字符串写入图像。在保持 LaTeX 格式的同时,我无法为变量设置任意精度。

这是一个 MWE:

import matplotlib.pyplot as plt
# Define some variables names and values.
xn, yn, cod, prec, prec2 = 'r', 'p', 'abc', 2, 4
ccl = [546.35642, 6785.35416]
ect = [12.5235, 13.643241]

plt.figure()

text1 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)

text = text1 + '\n' + text2
plt.text(0.5, 0.5, text)
plt.savefig('format_test.png', dpi=150)

这会引发错误KeyError: 't',因为它将子索引{t} 识别为变量。如果我改为使用:

text1 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(a=xn, ccl[0], ect[0], c=cod, p=prec)
text2 = "${{{a}}}_{t} = {:.{p}f} \pm {:.{p}f} {c}$".format(b=yn, ccl[1], ect[1], c=cod, p=prec2)

我得到SyntaxError: non-keyword arg after keyword arg,因为现在我在format 中定义了ccl[0], ect[0] 变量a=xn(第二个文本行相同)。

注意format 末尾的precprec2 值,它们决定了打印时数字的小数位数。我需要传递这个变量,因为它不是固定的,我不能只设置一个固定值来替换{:.{p}f}

如何使这些字符串行工作,同时保持 LaTeX 格式和所需的不同精度?

【问题讨论】:

    标签: python matplotlib latex string-formatting


    【解决方案1】:

    我认为您需要在 t 周围加上一个额外的花括号。这对我有用:

    text1 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(xn, ccl[0], ect[0], c=cod, p=prec)
    text2 = r"${}_{{t}} = {:.{p}f} \pm {:.{p}f} {c}$".format(yn, ccl[1], ect[1], c=cod, p=prec2)
    

    添加双花括号意味着它们被逐字处理,而不是作为 python 格式语法的一部分

    【讨论】:

    • 这是新格式语言的一个主要缺点,它与 Latex 的配合非常糟糕。
    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 2010-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-01
    相关资源
    最近更新 更多