gpt4 book ai didi

Python 转义原始字符串中的反斜杠

转载 作者:行者123 更新时间:2023-12-05 07:28:25 24 4
gpt4 key购买 nike

我想在我的 matplotlib 绘图中使用 latex 。到目前为止,这是可行的 -- 但现在反斜杠使事情变得困难。

这是我尝试过的:

r'$a_{{\text{{test}}}}$ ({})'.format('foo')
Out[13]: '$a_{\\text{test}}$ (foo)'

但我的预期输出是

'$a_{\text{test}}$ (foo)'

我已经尝试了很多方法来解决这个问题,但都无济于事:在原始环境中转义反斜杠自然会创建其中的 4 个。我如何获得预期的单反斜杠?


根本不起作用的是在 matplotlib 中绘制它

import matplotlib.pyplot as plt
plt.plot(np.array([1, 1]), label=r'$a_{{\text{{test}}}}$ ({})'.format('foo'))
plt.legend()

这会导致以下错误:

RuntimeError: latex was not able to process the following string:
b'$a_{\\\\text{test}}$ (foo)'
Here is the full report generated by latex:
This is pdfTeX, Version 3.14159265-2.6-1.40.18 (TeX Live 2017/Debian) (preloaded format=latex)
restricted \write18 enabled.
entering extended mode
(/home/saman/.cache/matplotlib/tex.cache/3d4d47cda002ea7b54e89aca2a4b3fae.tex
LaTeX2e <2017-04-15>
Babel <3.18> and hyphenation patterns for 84 language(s) loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2014/09/29 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo))
(/usr/share/texlive/texmf-dist/tex/latex/type1cm/type1cm.sty)
(/usr/share/texlive/texmf-dist/tex/latex/psnfss/helvet.sty
(/usr/share/texlive/texmf-dist/tex/latex/graphics/keyval.sty))
(/usr/share/texlive/texmf-dist/tex/latex/base/textcomp.sty
(/usr/share/texlive/texmf-dist/tex/latex/base/ts1enc.def))
(/usr/share/texlive/texmf-dist/tex/latex/geometry/geometry.sty
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifpdf.sty)
(/usr/share/texlive/texmf-dist/tex/generic/oberdiek/ifvtex.sty)
(/usr/share/texlive/texmf-dist/tex/generic/ifxetex/ifxetex.sty)
Package geometry Warning: Over-specification in `h'-direction.
`width' (5058.9pt) is ignored.
Package geometry Warning: Over-specification in `v'-direction.
`height' (5058.9pt) is ignored.
)
No file 3d4d47cda002ea7b54e89aca2a4b3fae.aux.
(/usr/share/texlive/texmf-dist/tex/latex/base/ts1cmr.fd)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
(/usr/share/texlive/texmf-dist/tex/latex/psnfss/ot1phv.fd)
! Undefined control sequence.
l.13 ...{10.000000}{12.500000}{\sffamily $a_{\text
{test}}$ (foo)}
No pages of output.
Transcript written on 3d4d47cda002ea7b54e89aca2a4b3fae.log.

最佳答案

你只有一个反斜杠。我不知道您如何查看字符串,但输出采用非原始字符串表示法,这就是您看到 \\ 的原因。但这只是为了演示目的。例如,输出还显示单引号 ('...'),它们实际上也不是字符串的一部分。

试试 print(r'$a_{{\text{{test}}}}$ ({})'.format('foo'))

关于Python 转义原始字符串中的反斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com