If I convert a Symbol to a string, the colon that is used to signify that it is a symbol is lost. For example,
julia> a = :abc
:abc
julia> string(a) # String does not have a colon
"abc"
I know I can create a very simple function to preserve the colon for Symbols but not alter the string formed for other variables but I was wondering if there is already an existing function for this.
The colon is not actually part of the Symbol object, which is why you donât get the colon when you create a String from it. Similar to how Vector is not part of the vector object itself when printing an array.
You can do ':' * string(a) to prepend the string with a colon.
To expand a bit on what I mean when I say âthe colon is not part of the symbolâ; contrary to popular belief, the prefixed colon is not the âmake this a symbolâ operator:
julia> a = :1
1
julia> a isa Symbol
false
julia> typeof(a)
Int64
Used like this, the colon is a quasi-quote operator. This gets a bit technical, but this more or less means âgive me the next fully-formed expression as the parser understands itâ. For numbers, that means giving back a numeric literal, for some text that means a symbol and so on.
The issue is the following - Symbol("foo bar") is a perfectly valid symbol! You canât produce it with :foo bar though, because the first fully formed expression after : is just foo:
julia> :foo bar
ERROR: ParseError:
# Error @ REPL[6]:1:5
:foo bar
# ââââ ââ extra tokens after end of expression
Stacktrace:
[1] top-level scope
@ none:1
(thanks to @c42f for the amazing PR on the most recent master branch! Itâs very useful to explain things like this).
Similarly, Symbol("1") is a perfectly valid symbol, yet you canât get it by writing :1 because that returns an integer literal, as shown above.
So while I donât know why you want the prefixed colon, note that itâs not part of the symbol; Iâm not sure prefixing it in strings you create from a symbol is going to achieve what youâre ultimately trying to do. While repr doesnât always give a leading : (and it canât), itâs likely going to be what youâre looking for anyway.
@Sukera: Thanks for the expanded reply. My usage is to print Dict key, value info where the key can be a Symbol like :orientation . I want the output to include the colon to alert the user that the key is a Symbol. There will not be any keys like Symbol("1") so indeed, for my purposes, repr() looks to be what I need.
As far as I understand, the show(something) function sends to the stdout (the screen) âsomethingâ but returns nothing.
julia> show(a)
:foo
Introducing this as an argument to the string function produces the output of the show() function, because the argument is executed, and transforms the returned value into a string, ie ânothingâ.