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

时间:2018-11-18 10:45:45

标签: python

我想在带有matplotlib的地块中使用乳胶。到目前为止,这是可行的-但现在反斜杠使事情变得困难。

这是我尝试过的:

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.

2 个答案:

答案 0 :(得分:0)

一旦格式化,则格式不是原始的。输出正常。 尝试将其存储到变量中,然后打印。

s = r"\{}"
print(s)
res = s.format("foo")
print(res)

答案 1 :(得分:0)

您只有一个反斜杠。我不知道您如何看待您的字符串,但是输出的格式不是原始字符串,这就是为什么您看到\\的原因。但这只是出于演示目的。例如,输出还显示单引号('...'),单引号也不是字符串的一部分。

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