How do you write special characters (“\\n”,“\\b”,…) to a file in Python?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-06 00:22:15

One solution is to escape the escape character (\). This will result in a literal backslash before the b character instead of escaping b:

with open(fileout,'w',encoding='utf-8') as fout:
    fout.write("\\begin{enumerate}[1.]\n")

This will be written to the file as

\begin{enumerate}[1.]<newline>

(I assume that the \n at the end is an intentional newline. If not, use double-escaping here as well: \\n.)

You just need to double the backslash: \\n, \\b. This will escape the backslash. You can also put the r prefix in front of your string: r'\begin'. As detailed here, this will prevent substitutions.

You can also use raw strings:

with open(fileout,'w',encoding='utf-8') as fout:
    fout.write(r"\begin{enumerate}[1.]\n")

Note the 'r' before \begin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!