I need, in Julia to write in a file, a LaTeX command, here is a minimal example :
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
You've understand what I want, I'd like to have a string with a backslash in it, but not as an escape character. This doesn't work :
julia> "\" # Error
neither this
julia> "\\\hline"
You can write "\\hline" to get what you want. In general the rule is that two \ get converted to one \ in the resulting string, so "\\\h" is an error, because it gets parsed as "\\" and then "\h" and \h is an invalid sequence, but e.g. "\\\r" would be accepted as \r is a valid espace sequence (so actually you had luck that \h is invalid as it allwed you to spot the error).
Also this means that if you want to have something\\+newline in the output you have to write ""something \\\\\n"" (five \ - four to get "\\" and fifth to get a new line with \n).
You can use a raw string literal to avoid having to escape \ like this: raw"\hline" (but you loose the ability to interpolate then). . See https://docs.julialang.org/en/latest/manual/strings/#man-raw-string-literals-1 for a corner case with \ at the end of the string.
You might also be interested in this package https://github.com/stevengj/LaTeXStrings.jl if you work with LaTeX a lot.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With