如何转义通过用户输入收到的乳胶代码? [英] How can I escape latex code received through user input?

查看:40
本文介绍了如何转义通过用户输入收到的乳胶代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从用户输入的 GUI 文本框中读取字符串,并通过 pandoc 处理它.该字符串包含具有反斜杠字符的数学乳胶指令.我想将字符串作为原始字符串发送给 pandoc 进行处理.但是像\theta"这样的东西变成了一个标签和heta".

I read in a string from a GUI textbox entered by the user and process it through pandoc. The string contains latex directives for math which have backslash characters. I want to send in the string as a raw string to pandoc for processing. But something like "\theta" becomes a tab and "heta".

如何将包含反斜杠字符的字符串文字转换为原始字符串...?

How can I convert a string literal that contains backslash characters to a raw string...?

感谢 develerx、飞羊和 unutbu.但似乎没有一个解决方案对我有帮助.原因是还有其他反斜杠字符在 python 中没有任何影响,但在乳胶中确实有意义.

Thanks develerx, flying sheep and unutbu. But none of the solutions seem to help me. The reason is that there are other backslashed-characters which do not have any effect in python but do have a meaning in latex.

例如'\lambda'.建议的所有方法都会产生

For example '\lambda'. All the methods suggested produce

\\lambda

在乳胶处理中没有经过——它应该保持为 \lambda.

which does not go through in latex processing -- it should remain as \lambda.

另一个

如果我能得到这份工作,我想我应该通过.@Mark:这三种方法都给出了我不想要的答案.

If i can get this work, i think i should be through. @Mark: All three methods give answers that i dont desire.

a='\nu + \lambda + \theta'; 
b=a.replace(r"\\",r"\\\\"); 
c='%r' %a; 
d=a.encode('string_escape');
print a

u + \lambda +   heta
print b

u + \lambda +   heta
print c
'\nu + \\lambda + \theta'
print d
\nu + \\lambda + \theta

推荐答案

Python 的原始字符串只是告诉 Python 解释器它应该将反斜杠解释为字面斜杠的一种方式.如果您阅读用户输入的字符串,则它们已经超出了原始状态.此外,用户输入很可能是按字面意思读取的,即原始".

Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. "raw".

这意味着翻译发生在其他地方.但如果你知道它发生了,为什么不逃避解释它的反斜杠呢?

This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?

s = s.replace("\\", "\\\\")

(请注意,您不能将 r"\" 作为 原始字符串不能以单个反斜杠结尾",但我也可以使用 r"\\" 作为第二个参数.)

(Note that you can't do r"\" as "a raw string cannot end in a single backslash", but I could have used r"\\" as well for the second argument.)

如果这不起作用,您的用户输入是出于某种解释反斜杠的神秘原因,因此您需要一种方法来告诉它停止这样做.

If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.

这篇关于如何转义通过用户输入收到的乳胶代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆