Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raw literal strings in Julia

In Python one can write r"a\nb" in order to prevent the \n from being interpreted as an escape sequence for newline.

Is there something similar in Julia? And what about string interpolation like "$variable", is there a way to prevent it?

I know one can simply write "a\\nb" and "\$variable" in Julia, but I would like to write a lot of LaTeX strings without having to care to proper escape every backslash \ and dollar $ characters...

(In Julia, r"..." creates a regular expression.)

like image 956
Cristóvão D. Sousa Avatar asked Feb 19 '14 13:02

Cristóvão D. Sousa


People also ask

What is a raw string literal?

Raw String Literal in C++ A Literal is a constant variable whose value does not change during the lifetime of the program. Whereas, a raw string literal is a string in which the escape characters like ' \n, \t, or \” ' of C++ are not processed. Hence, a raw string literal that starts with R”( and ends in )”.

How do you know if strings are equal in Julia?

The cmp() is an inbuilt function in julia which is used to return 0 if the both specified strings are having the same length and the character at each index is the same in both strings, return -1 if a is a prefix of b, or if a comes before b in alphabetical order and return 1 if b is a prefix of a, or if b comes before ...

Are strings mutable in Julia?

Since strings are immutable in Julia, and immutable means you can't change them, you can't change the characters in a string whilst keeping them of type string. If you want to be able to change the characters directly, you need to use something other than a string, e.g. an array of characters as explained above.


1 Answers

Ok, I just found out that since one can easily create non-standard string literals in Julia, a pass-through one will do what I was asking for:

macro R_str(s)
    s
end

>>> R"$a\n$b"
"\$a\\n\$b"
>>> print(R"$a\n$b")
$a\n$b

I also discovered that PyPlot.jl defines a «LaTeXString type which can be constructed via L"...." without escaping backslashes or dollar signs», with the additional benefit of rendered equations in IJulia.

A last question remains: is not worth it to have a raw string literal in Julia base?

like image 198
Cristóvão D. Sousa Avatar answered Oct 06 '22 14:10

Cristóvão D. Sousa