I am trying to define a string in Julia like I would in Python by doing the following:
'hello world'
However, I am getting the following error:
ERROR: syntax: character literal contains multiple characters
Stacktrace:
[1] top-level scope
# none:1
Any suggestion to resolve this? I searched around for the error but nothing about Julia came up, only C# and other languages.
Your answer is not complete without noting that in Julia you have also """
help?> """
""" is used to delimit string literals. Strings created by triple quotation marks
can contain " characters without escaping and are dedented to the level of the
least-indented line. This is useful for defining strings within code
that is indented.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> """Hello World!"""
"Hello World!"
julia> """Contains "quote" characters"""
"Contains \"quote\" characters"
julia> """
Hello,
world."""
"Hello,\nworld."
In languages like Python, it is possible to define a string with a single quote like this:
'this is a valid python string'
However, in Julia, the single quote can only be used for an individual character. If you have more than one, you need to use double quotes:
"This is a valid Julia string"
#vs
'This is NOT a valid string'
Related
Based on the relevant section of the Julia docs, my understanding is that a non-standard string literal like foo"hello, world" is equivalent to explicitly calling the corresponding macro: #foo_str("hello, world"). However, there must be some extra magic that I'm not understanding. Consider a date format dateformat"\m". By itself, "\m" throws a syntax error:
julia> "\m"
ERROR: syntax: invalid escape sequence
And the same syntax error is thrown if I call #dateformat_str("\m"), since the string literal "\m" appears to be evaluated or error checked before it is passed to the macro:
julia> using Dates
julia> #dateformat_str("\m")
ERROR: syntax: invalid escape sequence
However, using the non-standard string literal works:
julia> dateformat"\m"
dateformat"\m"
This is counter-intuitive, because I thought that dateformat"\m" was equivalent to #dateformat_str("\m"). How does the non-standard string literal avoid the syntax error generated by the standard string literal?
In short, because the parser recognizes that situation and parses the string literal differently
For string macros invocations it does this.
Calling: parse-raw-literal
Where as for normal string literals it does this.
Calling parse-string-literal
#dateformat_str("\m") on the other hand parses as a macro invocation on a normal string literal. so it uses the later parse-string-literal, which errors.
Note that ones parsed it has parsed the string into what is escaped as "\\m"
julia> dump(:(dateformat"\m"))
Expr
head: Symbol macrocall
args: Array{Any}((3,))
1: Symbol #dateformat_str
2: LineNumberNode
line: Int64 1
file: Symbol REPL[6]
3: String "\\m
Of related interest is the raw string macro , which does nothing at all, but is still going to be string parsed using parse-raw-literal
It is basically defined as
macro raw_str(s)
return s
end
I'm trying to create a string literal representing a CSV file with quoted fields. The intended CSV looks like this:
"a","b"
"1","2"
Triple quotes work if I want a newline character at the end of the string:
julia> """
"a","b"
"1","2"
"""
"\"a\",\"b\"\n\"1\",\"2\"\n"
But if I try to make a string without the newline character at the end, then I get a syntax error:
julia> """
"a","b"
"1","2""""
ERROR: syntax: cannot juxtapose string literal
Is there a simple way to get around this?
As an aside, note that there is no syntax error when you start the string-literal with a quote:
julia> """"a","b"
"1","2"
"""
"\"a\",\"b\"\n\"1\",\"2\"\n"
The issue is that this by itself is a valid string literal:
"""
"a","b"
"1","2"""
When you follow that with another " the parser thinks "woah, you can’t just follow a string with another string". You can force it to not consider the quote after 2 as part of a closing """ sequence by escaping it with \:
"""
"a","b"
"1","2\""""
At the start of the string, there's no such issue since the first three " characters are taken to start a string literal and the following " must just be a quote character inside of the string, which is what you want.
I'm not sure what you would consider the best solution to be. The options are:
Escape the " at the end;
Put the closing """ on a separate line.
The latter seems better to me, but it's your call.
See the Julia Docs for other examples on Triple-Quoted String Literals.
Julia has docstrings capabilities, which are documented here https://docs.julialang.org/en/stable/manual/documentation/. I'm under the impression that it has support for LaTeX code, but I'm not sure if the intention is that the LaTeX code should look like code or like an interpretation. In the following, the LaTeX code is garbled somewhat (see rho, for instance) and not interpreted (rho does not look like ρ). Am I doing something wrong?
Is there a way to get LaTeX code look interpreted?
What I mean by interpreted is something like what they do at https://math.stackexchange.com/.
The documentation says that LaTeX code should be wrapped around double back-quotes and that Greek letters should be typed as ρ rather than \rho. But that rather defeats the point of being able to include LaTeX code, doesn't it?
Note: Version 0.5.2 run in Juno/Atom console.
"""
Module blabla
The objective function is:
``\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt``
"""
module blabla
end
If I then execute the module and query I get this:
With triple quotes, the dollar signs disappear, but the formula is printed on a dark background:
EDIT Follow-up to David P. Sanders' suggestion to use the Documenter.jl package.
using Documenter
doc"""
Module blabla
The objective function is:
$\max \mathbb{E}_0 \int_0^{\infty} e^{-\rho t} F(x_t) dt$
"""
module blabla
end
Gives the following: the LaTeX code appears to print correctly, but it's not interpreted (ρ is displayed as \rho. I followed suggestions in: https://juliadocs.github.io/Documenter.jl/stable/man/latex.html to
Rendering LaTeX code as actual equations has to be supported by whichever software renders your docstrings. So, the short answer to why you're not seeing any rendered equations in Juno is that LaTeX rendering is currently not supported in Juno (as Matt B. pointed out, there's an open issue for that).
The doc"" string literal / string macro is there to get around another issue. Backslashes and dollar signs normally have a special meaning in string literals -- escape sequences and variable interpolation, respectively (e.g. \n gets replaced by a newline character, $(variable) inserts the value of variable into the string). This, of course, clashes with the ordinary LaTeX commands and delimiters (e.g. \frac, $...$). So, to actually have backslashes and dollar signs in a string you need to escape them all with backslashes, e.g.:
julia> "\$\\frac{x}{y}\$" |> print
$\frac{x}{y}$
Not doing that will either give an error:
julia> "$\frac{x}{y}$" |> print
ERROR: syntax: invalid interpolation syntax: "$\"
or invalid characters in the resulting strings:
julia> "``\e^x``" |> print
``^x``
Having to escape everything all the time would, of course, be annoying when writing docstrings. So, to get around this, as David pointed out out, you can use the doc string macro / non-standard string literal. In a doc literal all standard escape sequences are ignored, so an unescaped LaTeX string doesn't cause any issues:
julia> doc"$\frac{x}{y}$" |> print
$$
\frac{x}{y}
$$
Note: doc also parses the Markdown in the string and actually returns a Base.Markdown.MD object, not a string, which is why the printed string is a bit different from the input.
Finally, you can then use these doc-literals as normal docstrings, but you can then freely use LaTeX syntax without having to worry about escaping everything:
doc"""
$\frac{x}{y}$
"""
function foo end
This is also documented in Documenter's manual, although it is not actually specific to Documenter.
Double backticks vs dollar signs. The preferred way to mark LaTeX in Julia docstrings or documentation is by using double backticks or ```math blocks, as documented in the manual. Dollar signs are supported for backwards compatibility.
Note: Documenter's manual and the show methods for Markdown objects in Julia should be updated to reflect this.
You can use
doc"""
...
"""
This is a "non-standard string literal" used by the Documenter.jl package; see https://docs.julialang.org/en/stable/manual/strings/#non-standard-string-literals.
It seems ",", "$", "/" all serve as a separator, but "_" not.
x = "1"
"$x,x", "$x$x", "$x/1", "$x_1"
Is there any doc about this?
I believe this is because x_1 is a valid variable name in Julia, so it is trying to insert the value of that variable into the string.
The doc says:
The shortest complete expression after the $ is taken as the expression whose value is to be interpolated into the string
The internal workings are explained in the github issue #455 which could be summarised by:
The way string interpolation works is actually entirely defined in Julia. What happens is that the parser (in FemtoLisp) scans the code and finds a string literal, delimited by double quotes. If it finds no unescaped $ in the string, it just creates a string literal itself — ASCIIString or UTF8String depending on the content of the string. On the other hand, if the string has an unescaped $, it punts and hands the interpretation of the string literal to the str julia macro, which generates an expression that constructs the desired strings by concatenating string literals and interpolated values. This is a nice elegant scheme that lets the parser not worry about stuff like interpolation.
I could guess that #\, #\) #\] #\} #\; which are ,, ), ], } and ; respectively are closing tokens for expressions and $ is specifying the start of next interpolation.
I would like to know how to accommodate more than two types of quotes in a same row in R. Let´s say that I want to print:
'first-quote-type1 "first-quote-type2 "second-quote-type2
'sencond-quote-type1
Using one quote in the beginning and one in the end we have:
print("'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1")
Error: unexpected symbol in "print("'first-quote-type1 "first"
I tried to include triple quotes as required in Python in this cases:
print(''''first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1''')
print("""'first-quote-type1 "first-quote-type2 "second-quote-type2 'sencond-quote-type1""")
However, I also got a similar error. Some idea how to make this syntax work in R?
To use a quote within a quote you can escape the quote character with a backslash
print("the man said \"hello\"")
However, the print function in R will always escape character.
To not show the escaped character use cat() instead
so...
cat("the man said \"hello\"") will return
the man said "hello"