Julia - 在文件中打印或写入字符串中的反斜杠

JKH*_*KHA 3 string backslash julia

我需要在 Julia 中写入一个文件,一个 LaTeX 命令,这是一个最小的例子:

open("./file.tex", "w") do f
   foo::Int = 5
   # write(f, "$foo\hline \n")        - This is what I would like to do
   # write(f, "$foo \\ \n")           - This is another thing I want to do, and it works
   # write(f, "$foo \\\hline \n")     - My final goal is this -> 
                                        leads to ERROR: syntax: invalid escape sequence
end
Run Code Online (Sandbox Code Playgroud)

你已经明白我想要什么了,我想要一个带有反斜杠的字符串,但不是作为转义字符。这不起作用:

julia> "\"  # Error
Run Code Online (Sandbox Code Playgroud)

既不是这个

julia> "\\\hline"
Run Code Online (Sandbox Code Playgroud)

Bog*_*ski 6

你可以写"\\hline"来得到你想要的。在一般的规则是两个\地转化为一个\结果字符串中,所以"\\\h"是错误的,因为它被解析为"\\",然后"\h"\h是一个无效的序列,但如"\\\r"将作为被接受\r是一个有效的协商序列(所以实际上你有运气\h是无效的,因为它可以让您发现错误)。

这也意味着,如果你想在输出中有something\\+newline你必须写""something \\\\\n""(五\- 四得到"\\",第五得到一个新行\n)。

您可以使用原始字符串文字来避免\像这样转义:(raw"\hline"但是您失去了插入的能力)。. 请参阅https://docs.julialang.org/en/latest/manual/strings/#man-raw-string-literals-1\了解字符串末尾的极端情况。

如果您经常使用 LaTeX,您可能也对这个包https://github.com/stevengj/LaTeXStrings.jl感兴趣。